Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Flatten an array in Javascript without recursion
'use strict'
var Benchmark = require('benchmark')
var suite = new Benchmark.Suite;
var list = [1, 2, 3, [[4]], [[[5]]], [6], [[7]]]
function flattenRecursive (list) {
var flatList = []
list.forEach(function (item) {
if (item instanceof Array === true) {
flatList = flatList.concat(flattenRecursive(item))
} else {
flatList.push(item)
}
})
return flatList
}
function flatten (list) {
var flatList = []
while (list.length) {
var item = list.shift()
if (item instanceof Array === true) {
list = item.concat(list)
} else {
flatList.push(item)
}
}
return flatList
}
suite.add('flattenRecursive', function() {
flattenRecursive(list.slice())
})
.add('flatten', function() {
flatten(list.slice())
})
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.