How do you split an array into array pairs in JavaScript?

后端 未结 14 1577
广开言路
广开言路 2020-12-08 09:49

I want to split an array into pairs of arrays.

var arr = [2, 3, 4, 5, 6, 4, 3, 5, 5]

would be

var newarr = [
    [2, 3],
           


        
相关标签:
14条回答
  • 2020-12-08 10:32

    Here's another solution using lodash helpers:

    function toPairs(array) {
      const evens = array.filter((o, i) => i % 2);
      const odds = array.filter((o, i) => !(i % 2));
      return _.zipWith(evens, odds, (e, o) => e ? [o, e] : [o]);
    }
    console.log(toPairs([2,3,4,5,6,4,3,5,5]));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>

    0 讨论(0)
  • 2020-12-08 10:34

    You can use js reduce

    initialArray.reduce(function(result, value, index, array) {
      if (index % 2 === 0)
        result.push(array.slice(index, index + 2));
      return result;
    }, []);
    
    0 讨论(0)
提交回复
热议问题