在 JavaScript 中如何将数组拆分为数组对?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31352141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:34:10  来源:igfitidea点击:

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

javascriptarrays

提问by Tormod Smith

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],
    [4, 5],
    [6, 4],
    [3, 5],
    [5]
]

回答by Vbyec

You can use js reduce

您可以使用 js减少

initialArray.reduce(function(result, value, index, array) {
  if (index % 2 === 0)
    result.push(array.slice(index, index + 2));
  return result;
}, []);

回答by ChadF

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;
};

回答by vinniecent

Lodash has a method for this: https://lodash.com/docs/4.17.10#chunk

Lodash 有一个方法:https://lodash.com/docs/4.17.10#chunk

_.chunk([2,3,4,5,6,4,3,5,5], 2); // => [[2,3],[4,5],[6,4],[3,5],[5]]

_.chunk([2,3,4,5,6,4,3,5,5], 2); // => [[2,3],[4,5],[6,4],[3,5],[5]]

回答by Matt Lacey

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));
}

回答by Jason Cust

A slightly different approach than using a forloop for comparison. To avoid modifying the original array slicemakes a shallow copy since JS passes objects by reference.

与使用for循环进行比较的方法略有不同。为了避免修改原始数组slice,因为 JS 通过引用传递对象,所以进行浅拷贝。

function pairArray(a) {
  var temp = a.slice();
  var arr = [];

  while (temp.length) {
    arr.push(temp.splice(0,2));
  }

  return arr;
}

var array = [2,3,4,5,6,4,3,5,5];
var newArr = pairArray(array);

function pairArray(a) {
  var temp = a.slice();
  var arr = [];

  while (temp.length) {
    arr.push(temp.splice(0,2));
  }

  return arr;
}

document.write('<pre>' + JSON.stringify(newArr) + '</pre>');

回答by Mark T

I would use lodashfor situations like this.

我会在这种情况下使用lodash

Here is a solution using _.reduce:

这是使用的解决方案_.reduce

var newArr = _(arr).reduce(function(result, value, index) {
  if (index % 2 === 0)
    result.push(arr.slice(index, index + 2));

  return result;
}, []);

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

var newArr = _(arr).reduce(function(result, value, index) {
  if (index % 2 === 0)
    result.push(arr.slice(index, index + 2));
  
  return result;
}, []);

document.write(JSON.stringify(newArr)); // [[2,3],[4,5],[6,4],[3,5],[5]]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script>

回答by alden

Here's another solution using lodash helpers:

这是使用 lodash 助手的另一个解决方案:

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>

回答by doeke

It's possible to group an array into pairs/chunks in one line without libraries:

可以在没有库的情况下在一行中将数​​组分组为成对/块:

function chunks(arr, size = 2) {
  return arr.map((x, i) => i % size == 0 && arr.slice(i, i + size)).filter(x => x)
}
console.log(chunks([1, 2, 3, 4, 5, 6, 7])) // -> [[1, 2], [3, 4], [5, 6], [7]]

回答by Simon Buchan

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

现在有灵活的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?):

并且可能更有效,但看起来很傻Array.from(source, mapfn?)

const pairs = Array.from({ length: arr.length / 2 }, (_, i) => arr.slice(i * 2, i * 2 + 2))

回答by chirag

const items = [1, 2, 3, 4, 5];

const createBucket = (bucketItems, bucketSize) => buckets => {
  return bucketItems.length === 0 ? buckets : [...buckets, bucketItems.splice(0, bucketSize)];
};

const bucketWithItems = items.reduce(createBucket([...items], 4), []);