DEV Community

Andrew S.
Andrew S.

Posted on • Edited on

Single-Line JavaScript Methods

1. Selecting a random element from an array.

// Input: [1, 2, 3, 4]
const randomElement = arr => arr[Math.floor(Math.random() * arr.length)];
// Output: Something like 2, or 4, or 1... you get it.
Enter fullscreen mode Exit fullscreen mode

2. Getting rid of duplicate array elements.

// Input: [1, 2, 2, 3]
const uniqueArray = [...new Set([1, 2, 2, 3])];
// Output: [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

3. Sorting array objects by a specific property.

// Input: 'name', [{name:'Bob', age:25}, {name:'Alice', age:22}]
const sortBy = (arr, key) => arr.sort((a, b) => a[key] > b[key] || -1);
// Output: [{name:'Alice', age:22}, {name:'Bob', age:25}]
Enter fullscreen mode Exit fullscreen mode

4. Checking the equality of two arrays or objects.

// Input: [1, 2], [1, 2]
const arraysEqual = JSON.stringify([1, 2]) === JSON.stringify([1, 2]);
// Output: true
Enter fullscreen mode Exit fullscreen mode

5. Make the code wait for a certain time.

const chill = ms => new Promise(resolve => setTimeout(resolve, ms));

(async () => {
  console.log("Before waiting");
  await chill(2000);
  console.log("After waiting for 2 seconds");
})();
Enter fullscreen mode Exit fullscreen mode

6. Extracting a property from an array of objects.

const pluck = (arr, key) => arr.map(obj => obj[key]);
console.log(pluck([{x: 1}, {x: 2}], 'x')); // Output: [1, 2]
Enter fullscreen mode Exit fullscreen mode

7. Insert an element into a specific position.

// Input: [1, 2, 4]
const insert = (arr, index, newItem, a=[...arr]) => (a.splice(index, 0, newItem), a);
// Output: [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

8. Generate a random HEX colour code.

// Input: No input needed
const randomColor = "#" + (~~(Math.random() * 8**8)).toString(16).padStart(6, 0);
// Output: Something like #f5a623
Enter fullscreen mode Exit fullscreen mode

Support ❤️

It took a lot of time and effort to create this material. If you found this article useful or interesting, please support my work with a small donation. It will help me to continue sharing my knowledge and ideas.

Make a contribution or Subscription to the author's content: Buy me a Coffee, Patreon, PayPal.

Top comments (0)