Javascript is one of the most powerful language in this modern world.In this article we will go through some of the useful js one-liners.
Remove Duplicates in an Array.
const array = [12, 23, 54, 69, 4, 12, 23];
console.log(array); // [12, 23, 54, 69, 4, 12, 23]
const RemoveDuplicates = (arr) => [...new Set(arr)];
console.log(RemoveDuplicates(array)); // [12, 23, 54, 69, 4]
Generate a random Id
const randomId = Math.random().toString(36).substring(2);
console.log(randomId); // ituzp41cq08
shuffle an Array
const alpha = ["A", "B", "C", "D", "E", "F"];
console.log(alpha); // ["A", "B", "C", "D", "E", "F"]
console.log(alpha.slice().sort(() => Math.random() - 0.5)); // ["B", "A", "C", "E", "F", "D"]
Swapping two variables
let a = 10;
let b = 5;
console.log(a, b); // 10 5
[a, b] = [b, a];
console.log(a, b); // 5 10
Assign Multiple variables
let [x, y, z, w] = [4, 0.5, "Ajith", ["a", "b"]];
console.log(x, y, z, w); //4 0.5 "Ajith" ["a", "b"]
Reverse a String
const reverseString = (arr) => arr.split("").reverse().join("");
console.log(reverseString("I love to code in javascript")); //tpircsavaj ni edoc ot evol I
Merge multiple arrays
const languages = ["js", "c", "go", "java"];
const frameworks = ["react", "angular", "ruby on rails", "larvel"];
const combined = languages.concat(frameworks);
console.log(combined); //["js", "c", "go", "java", "react", "angular", "ruby on rails", "larvel"]
Top comments (5)
Nice post. Be aware that shuffling an Array like this is not perfectly random and a proper implementation is a little more complicated: medium.com/@nitinpatel_20236/how-t...
In case anyone is interested, I plotted the distributions for the
Math.random() - 0.5
and the Fisher-Yates shuffles.That's 100000 shuffles of
abcd
for each algorithm.Very interesting, I hadn't considered how using
sort
like that could end up with an infinite loop!nice job man
Awesome thanks