daylennguyen
12/20/2019 - 5:05 PM

Useful Array One-liners.

Useful Array One-liners.

// Remove Duplicates from an array
const removeDuplicates =
  arr => arr.filter((item, index) => index === arr.indexOf(item));

const removeDuplicates1 = array => [...new Set(array)];

const removeDuplicates2 = array => Array.from(new Set(array));


// Flattens an array(doesn't flatten deeply).
const flatten = array => [].concat(...array);

const flattenDeep =
  arr => arr.reduce((fArr, item) =>
    fArr.concat(Array.isArray(item) ? flatten(item) : item), []);

// Merge arrays
const merge = (...arrays) => [].concat(...arrays);

// Pipe fn
const pipe = (...fns) => arg => fns.reduce((v, fn) => fn(v), arg);

// Generates range [start, end) with step
const range = (start, end, step = 1) =>
  Array.from({ length: Math.ceil((end - start) / step) }, (_, i) => start + i * step);

// Generates random hex color code.
const color = () => '#' + Math.floor(Math.random() * 0xffffff).toString(16);