How do you split an array into array pairs in Java

2020-02-03 09:10发布

I want to split an array into pairs of arrays

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

would be newarr =[[2,3],[4,5],[6,4],[3,5],[5]]

12条回答
Lonely孤独者°
2楼-- · 2020-02-03 09:37

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;
}, []);
查看更多
疯言疯语
3楼-- · 2020-02-03 09:37

There's no pre-baked function to do that, but here's a simple solution:

var splitPairs = function(arr) {
    var pairs = [];
    for (var i=0 ; i<arr.length ; i+=2) {
        if (arr[i+1] !== undefined) {
            pairs.push ([arr[i], arr[i+1]]);
        } else {
            pairs.push ([arr[i]]);
        }
    }
    return pairs;
};
查看更多
Emotional °昔
4楼-- · 2020-02-03 09:39

Here is a short and more generic solution:

function splitArrayIntoPairs(arr, n) {
 var len = arr.length
  var pairs = []

  for (let i = 0; i < len; i += n) {
    var temp = []
    for (var j = i; j < (i + n); j++) {
      if (arr[j] !== undefined) {
        temp.push(arr[j])
      }
    }
    pairs.push(temp)
  }
  return pairs
}

Where arr is your array and n is no of pairs

查看更多
叼着烟拽天下
5楼-- · 2020-02-03 09:39

Yet another that's a bit of a mish-mash of the already-posted answers. Adding it because having read the answers I still felt things could be a little easier to read:

var groups = [];

for(var i = 0; i < arr.length; i += 2)
{
    groups.push(arr.slice(i, i + 2));
}
查看更多
干净又极端
6楼-- · 2020-02-03 09:40

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>

查看更多
看我几分像从前
7楼-- · 2020-02-03 09:41

There is now the flexible Array#flatMap(value, index, array):

const pairs = arr.flatMap((_, i, a) => i % 2 ? [] : [a.slice(i, i + 2)]);

And the possibly more efficient, but goofy looking Array.from(source, mapfn?):

const pairs = Array.from({ length: arr.length / 2 }, (_, i) => arr.slice(i * 2, i * 2 + 2))
查看更多
登录 后发表回答