数组操作-数组扁平化

Benchmark created on


Test runner

Ready to run.

Testing in
TestOps/sec
forEach
function flatten(arr) {  
  var result = [];  
  arr.forEach(function(item) {  
    if (Array.isArray(item)) {  
      result = result.concat(flatten(item));  
    } else {  
      result.push(item);  
    }  
  });  
  return result;  
}
const arr = [1, [2, 3], 4, [5, 6, [7, 8]]];
flatten(arr);
ready
reduce
function flatten(arr) {
  return arr.reduce(function (acc, cur) {
    return acc.concat(Array.isArray(cur) ? flatten(cur) : cur);
  }, []);
}
const arr = [1, [2, 3], 4, [5, 6, [7, 8]]];
flatten(arr);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.