Last active
January 31, 2020 17:51
-
-
Save thetutlage/6d6bbbb68bbb5fa1facc318fd25e27e7 to your computer and use it in GitHub Desktop.
Flatten an array in Javascript without recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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() |
@thetutlage the solution with recursion is much faster when written in the right way :) https://jsperf.com/flatten-array-r1
@gauravmuk your link is 404
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@thetutlage I think the majority of the performance difference between the
flattenRecursive
andflatten
is that.forEach
is very slow. Try this:or how about how about: