10 JavaScript One-Liner Code You Should Know
Manjush
Posted on July 7, 2024
1. Deep clone object
This one-Liner will make a Deep clone of a javascript object:
const originalObject = {
"studentId": 26334,
"studentName":"John Doe",
"totalMarks": 348.50
};
const clonedObject = structuredClone(originalObject);
console.log("Student details: ", clonedObject);
// Output: { studentId: 26334, studentName: "John Doe", totalMarks: 348.5 }
2. Truncate a String To a Specific Length
This is One-Liner is to truncate a string and add "..." to an end on a specific given length
const originalString = "The quick brown fox jumps over the lazy dog";
const truncate = (str, len) => str?.length > len ? str.slice(0, len) + "..." : str;
console.log("Truncated string: ", truncate(originalString, 9));
// Output: The quick...
3. Remove duplicate elements in array
This one-Liner will return a new array without duplicate elements from original array
const originalArray = [9,'a',8,'a','b',9,5,3,9,3.5,'b'];
const removeDuplicates = arr => [...new Set(arr)]
console.log("Array without duplicates: ", removeDuplicates(originalArray));
// Output: [ 9, "a", 8, "b", 5, 3, 3.5 ]
3. Swap numbers
This one liner swaps 2 numbers:
let a=6, b=9;
[a,b] = [b,a]
console.log(`Swapped Values - a: ${a} b: ${b}`);
// Output: Swapped Values - a: 9 b: 6
4. Flatten a nested array
This one liner helps you to flatten a nested array
const flattenArray = (arr) => [].concat(...arr);
console.log("Flattened: ", flattenArray([1, [2, 5, 6], 7,6, [2,3]])
// Output: Flattened: [ 1, 2, 5, 6, 7, 6, 2, 3 ]
5. Scroll To Top
This one liner instantly navigates you to the top of the page:
window.scrollTo(0, 0)
6. Find the Last Occurrence in an Array:
This one liner returns last occurrence of element in an array:
const lastIndexOf = (arr, item) => arr.lastIndexOf(item);
console.log("Last index of 7 is: ", lastIndexOf([7, 5, 6 , 7 , 3 , 4], 7))
// Output: Last index of 7 is: 3
7. Make Your Code Wait for a Specific Time
Sometimes we want to make our code wait out for a seconds,
const waitForIt = ms => new Promise(resolve => setTimeout(resolve, ms));
(async () => {
console.log("Before waiting");
await waitForIt(5000);
console.log("After waiting for 5 seconds");
})();
/* Output:
Before waiting
Promise { <state>: "pending" }
After waiting for 5 seconds
*/
8. Extract a Property from an Array of Objects
Need to grab a specific property from an array of objects? Cherry-pick it!
const getValuesOfAKey = (arr, key) => arr.map(obj => obj[key]);
console.log("Values of a: ", getValuesOfAKey([{a: 1}, {a: 2}], 'a'));
// Output: Values of a: Array [ 1, 2 ]
9. Generate a Random Hexadecimal Color Code:
Get a random hex color code!
const randomColor = "#" + (~~(Math.random() * 8**8)).toString(16).padStart(6,0);
console.log("Generated code: ", randomColor);
// Output: Generated code: #0cf199
10. Remove falsy values from array
const removeFalsy = (arr) => arr.filter(Boolean);
// or as suggested by Jon Randy
const removeFalsy = arr => arr.filter(x=>x)
console.log("Without falsy:", removeFalsy([true, false, undefined, NaN, null, false, true]))
// Output: Without falsy: [ true, true ]
๐ ๐ช ๐
๐ฉ
Manjush
Posted on July 7, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.