DEV Community

Cover image for Some Powerful Js One-liners
Ajithmadhan
Ajithmadhan

Posted on

Some Powerful Js One-liners

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]
Enter fullscreen mode Exit fullscreen mode

Generate a random Id

const randomId = Math.random().toString(36).substring(2);
console.log(randomId); // ituzp41cq08
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

Do like and save this post for future reference πŸš€πŸ’―

Top comments (5)

Collapse
 
m90 profile image
Frederik Ring

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...

Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli • Edited

In case anyone is interested, I plotted the distributions for the Math.random() - 0.5 and the Fisher-Yates shuffles.

Chart of shuffle using Math.random() - 0.5. Shows clearly uneven distribution

Chart of Fisher-Yates shuffle algorithm. Shows a distribution much closer to even

That's 100000 shuffles of abcd for each algorithm.

Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli

Very interesting, I hadn't considered how using sort like that could end up with an infinite loop!

Collapse
 
yj445649862 profile image
前端狗

nice job man

Collapse
 
fahim525 profile image
Fahim Ahmed

Awesome thanks