Javascript in Powerful One Line Functions

 Remove duplicate values from an array

const remove Duplicates = (arr) => [...new Set (arr) ] ;
remove Duplicates ( [1, 2, 3, 3, 4, 4, 5, 5, 6]);
/ / Result: [ 1, 2, 3, 4, 5, 6]

A clever and simple way of obtaining unique values of an array by converting the given

array to a set and then making use of the spread operator to generate the result.

Copying text to the clipboard

const copy To Clipboard = (text) => navigator.clipboard .writeText (text) ; 
copyToClipboard("Woah! ");

You can use your browser’s built-in clipboard API to modify your user’s clipboard, the function takes a string parameter. You can do much more with the clipboard API, but this is a good example to start.

 Shuffling the values of an array

const shuffle = arr => arr.sort (() => 0.5 - Math.random () )

shuffle ([1, 2, 3, 4, 5]) // Returns Random Order




There are certain situations where you may want to randomize the elements in your array,
For example, shuffling a playlist, this is a simple one line function that sorts your array in a completely random order.


Generate a random hex color

const randomColor =( ) =>' #$(Math. random(). toString (16) . slice (2, 8). padEnd (6, '0'));

randomColor (); // Result: #ce fc54

Also great for those situations where you may want to add an element of surprise to your web page, this function uses template literals to generate a hex string that is random with each call.

Check if an element is in focus

const isFocused = (el) => (el === document. activeElement) ;
isFocused (element); // Result: true or false

When you want to check if a certain element is in focus on the page, you can do so using the document’s active Element property. This will return a true or false value that you can be used to build further logic for your app.

Leave a Reply

Your email address will not be published.