Categories
javascript nodejs

Javascript One-Liners

A few of my favorite JavaScript one-liners that can be used in your projects today.

// Largest number in an array
const largestNumber = arr => Math.max(...arr)
largestNumber([20, 99, 53, 10]) // 99
// Find the difference between two arrays
const findDiff = (arr1, arr2) => arr1.filter(item => !arr2.includes(item))
findDiff(['oliver', 'ashley', 'aldo'], ['oliver', 'ashley']) // aldo
// Create an object from an array of key-value pairs
const objectFromPairs = arr => Object.fromEntries(arr)
const entries = new Map([
  ['foo', 'bar'],
  ['baz', 42]
]);
objectFromPairs(entries) // { foo: 'bar', baz: 42 }
// Remove item from an array
const removeItem = (arr, item) => arr.filter(element => element !== item)
removeItem(['oliver', 'ashley', 'aldo'], 'aldo') // [ 'oliver', 'ashley' ]
// Calculate the sum of an array of numbers
const sumArr = arr => arr.reduce((total, num) => total + num, 0)
sumArr([10, 5, 1]) // 16
// Remove duplicates from an array using Set()
const uniqueArray = arr => [...new Set(arr)]
uniqueArray(['oliver', 'jules', 'oliver', 'john']) // [ 'oliver', 'jules', 'john' ]
// Check if a number is even
const isEven = num => num % 2 === 0
isEven(4) // true
// Remove false values
const removeFalse = (arr) => arr.filter(Boolean)
removeFalse([NaN, 'a string', '', 0, true, 5, undefined]) // [ 'a string', true, 5 ]
// Truncate a number to a fixed decimal point
const roundValue = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)
roundValue(4.005, 2)