One-lines

Just a collection of JavaScript one-line tips.

  • How to Capitalize Text

    const capitalize = (str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;

  • How to Calculate Percent

    const calculatePercent = (value, total) => Math.round((value / total) * 100)

  • How to Get a Random Element

    const getRandomItem = (items) =>  items[Math.floor(Math.random() * items.length)];

  • How to Remove Duplicate Elements

    const removeDuplicates = (arr) => [...new Set(arr)];

  • How to Sort Elements By Certain Property

  • How to Check if Arrays/Objects are Equal

  • How to Count Number of Occurrences

  • How to Wait for a Certain Amount of Time

  • How to Use the Pluck Property from Array of Objects

  • How to Insert an Element at a Certain Position


Reference

https://www.freecodecamp.org/news/javascript-one-liners-to-use-in-every-project/

Last updated