Skip to content

Instantly share code, notes, and snippets.

@nikoloza
Last active October 11, 2016 08:13
Show Gist options
  • Save nikoloza/8c55944ed7e547e4bd2b3c67587852d8 to your computer and use it in GitHub Desktop.
Save nikoloza/8c55944ed7e547e4bd2b3c67587852d8 to your computer and use it in GitHub Desktop.
Array Deep Flatten function
// example
var arr = [[1, 2, [3]], 4, 6, [1, [2, 4]], 6]
console.log(flatten(arr)) // => [1, 2, 3, 4, 6, 1, 2, 4, 6]

Array Deep Flatten function

Array flatten functionality in JavaScript. Used functional way of solving this task and it gives really cool performance (more than 2 times faster than setting as an Array method).

Here are unit and performance tests which are given in this gist also. For online view, see unit and performance tests on RequireBin (please check console for results). They are compared against lodash.flattendeep solution.

The code syntax is based on ES6 and Standard.

/**
* Flatten function
* @param {Array} arr - Original array to flatten.
* @param {Array} [newArr] - ES6 way to store new array.
* This also gives possibility to append on existing array.
* @example
* // returns [1, 2, 3, 4]
* flatten([[1, 2, [3]], 4])
* @returns {Array} Returns new flattened array.
*/
function flatten (arr, newArr = []) {
for (let i = 0; i < arr.length; i++) {
var val = arr[i]
if (typeof val === 'number') newArr.push(val)
else if (Array.isArray(val)) flatten(val, newArr)
}
return newArr
}
module.exports = flatten
const flatten = require('.')
const flattenDeep = require('lodash.flattendeep')
var startTime
var arr = [[1, 2, [3]], 4, 6, [1, [2, 4]], 6]
// stress test
console.log('stress test:')
// - flatten
startTime = performance.now()
for (let i = 0; i < 10000; i++) flatten(arr)
console.log('flatten', performance.now() - startTime)
// - lodash
startTime = performance.now()
for (let i = 0; i < 10000; i++) flattenDeep(arr)
console.log('lodash', performance.now() - startTime)
// big data
console.log('big data:')
arr = []
for (let i = 0; i < 10000; i++) arr[i] = Math.random()
// - flatten
startTime = performance.now()
flatten(arr)
console.log('flatten', (performance.now() - startTime))
// - lodash
startTime = performance.now()
flattenDeep(arr)
console.log('lodash', (performance.now() - startTime))
const flatten = require('.')
const test = require('tape')
const flattenDeep = require('lodash.flattendeep')
// tests
test('flatten function', (t) => {
t.plan(3)
var arr1 = [[1, 2, [3]], 4]
var arr2 = [[1, 2, [3]], 4, 6, [1, [2, 4]], 6]
var arr3 = [1, [2, 1, [1, 2, -1], [1]], 1, [2, 1]]
t.deepEqual(flatten(arr1), flattenDeep(arr1), 'arr1 is equal')
t.deepEqual(flatten(arr2), flattenDeep(arr2), 'arr2 is equal')
t.deepEqual(flatten(arr3), flattenDeep(arr3), 'arr3 is equal')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment