utils/array-utils/src/flatten.js

  1. /**
  2. * Flatten the given array into a single array of elements.
  3. * The given array can be composed of multiple depths of objects and or arrays.
  4. * @param {Array} array - array to flatten
  5. * @returns {Array} a flat array with a single list of elements
  6. * @alias module:array-utils.flatten
  7. * @example
  8. * const flat = flatten([[1], [2, 3, [4, 5]], 6]) // returns [1, 2, 3, 4, 5, 6]
  9. */
  10. const flatten = (arr) => arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), [])
  11. module.exports = flatten