DEV Community

Cover image for 🚴‍♂️Speeding up with JS one liners
Tarcísio Giroldo
Tarcísio Giroldo

Posted on

🚴‍♂️Speeding up with JS one liners

I will write more, I promise.
I've been doing some leetcode and practicing my typing. So I pretend to write more about these two subjects.
I'm also not generating these stuff with ChatGPT and pretend to write more of my thoughts instead just being some random subject IA generated.
BUT I'm guiding through other articles about one liners and I know that subject is really simple and have another articles that you can search here on dev.to

But that's it, I hope y'all like it and share with your friends.

Array

Remove false values from array

arr.filter(Boolean)
Enter fullscreen mode Exit fullscreen mode

Remove duplicates from array

[...new Set(input)]
Enter fullscreen mode Exit fullscreen mode

Swap between 2 elements

[a, b] = [b, a]
Enter fullscreen mode Exit fullscreen mode

Remove holes from array

input.flat(0)
Enter fullscreen mode Exit fullscreen mode

Casting to array of numbers

input.map(Numbers)
Enter fullscreen mode Exit fullscreen mode

Clone an array

input.slice(0)
Enter fullscreen mode Exit fullscreen mode
[...input]
Enter fullscreen mode Exit fullscreen mode
Array.from(input)
Enter fullscreen mode Exit fullscreen mode

Merge multiple arrays

(...input) => input.flat(1)
Enter fullscreen mode Exit fullscreen mode

Objects

Checking if the object is empty

Object.keys(obj).length === 0;
Enter fullscreen mode Exit fullscreen mode

Strings

Removing whitespaces in a string

str.replace(/\s/g, '');
Enter fullscreen mode Exit fullscreen mode

Generating random string

Math.random().toString(36).slice(2);
Enter fullscreen mode Exit fullscreen mode

Reverse a string

input.split('').reverse().join('')
Enter fullscreen mode Exit fullscreen mode

Numbers

Generate random integer

Math.floor((Math.random() * (max - min + 1)) + min)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)