最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is alternative way concat in js - Stack Overflow

programmeradmin0浏览0评论

I'm having a problem with my function flatten

Here's the code:

    function flatten(arrays) {
    return [].concat.apply([], arrays);
}

There's an error of max exceed so i tried to change the function to this:

    function flatten(arrays){
    return arrays.reduce(function(prev, curr){
        return prev.concat(curr);
    }, []);
}

the error was gone but its too slow. Is there alternative code for concat.

I'm having a problem with my function flatten

Here's the code:

    function flatten(arrays) {
    return [].concat.apply([], arrays);
}

There's an error of max exceed so i tried to change the function to this:

    function flatten(arrays){
    return arrays.reduce(function(prev, curr){
        return prev.concat(curr);
    }, []);
}

the error was gone but its too slow. Is there alternative code for concat.

Share Improve this question asked Nov 8, 2017 at 1:24 KelKel 553 silver badges12 bronze badges 5
  • 1 Max what exceeded? Are there too many arguments, or is the concatenated array too big? – RobG Commented Nov 8, 2017 at 1:33
  • What do you want ? Do you want to convert a multidimensional array to single dimensional? – A l w a y s S u n n y Commented Nov 8, 2017 at 1:38
  • You may want to look into using underscore's flatten. See github./jashkenas/underscore/blob/1.8.3/underscore.js#L490. It gives a better performance of all three. JSPerf: jsperf./flatten-arrays-perf/1 – Oluwafemi Sule Commented Nov 8, 2017 at 1:49
  • The flatten function seems to work with up to 10,000 elements in arrays (Safari, Chrome, Firefox). There is no limit to the number of arguments in ECMA-262, at what point do you get max whatever exceeded? – RobG Commented Nov 8, 2017 at 1:56
  • if you want to save some time to implement it. try using libraries such as lodash there is a method called flattenDeep _.flattenDeep(youArray); lodash./docs/#flattenDeep – John Michael Villegas Commented Nov 8, 2017 at 3:44
Add a ment  | 

1 Answer 1

Reset to default 5

Try this ES6 spread syntax:

const array1 = [1,2,3]
const array2 = [4,5,6]
const array3 = [...array1, ...array2]
console.log(array3)
发布评论

评论列表(0)

  1. 暂无评论