Skip to content

Instantly share code, notes, and snippets.

@iOnline247
Forked from thetutlage/flatten.js
Created April 27, 2016 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iOnline247/5b50515d5878f959d16f7dd522a39280 to your computer and use it in GitHub Desktop.
Save iOnline247/5b50515d5878f959d16f7dd522a39280 to your computer and use it in GitHub Desktop.
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 clonedList = list.slice(0)
var flatList = []
while (clonedList.length) {
var item = clonedList.shift()
if (item instanceof Array === true) {
clonedList = item.concat(clonedList)
} else {
flatList.push(item)
}
}
return flatList
}
suite.add('flattenRecursive', function() {
flattenRecursive(list)
})
.add('flatten', function() {
flatten(list)
})
.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