如何用JavaScript将一个长数组分割成更小的数组?

时间:2021-06-16 12:17:53

I have an array of e-mails (it can be just 1 email, or 100 emails), and I need to send the array with an ajax request (that I know how to do), but I can only send an array that has 10 or less e-mails in it. So if there is an original array of 20 e-mails I will need to split them up into 2 arrays of 10 each. or if there are 15 e-mails in the original array, then 1 array of 10, and another array of 5. I'm using jQuery, what would be the best way to do this?

我有一个电子邮件数组(可以是1封电子邮件,也可以是100封电子邮件),我需要发送一个ajax请求(我知道怎么做),但我只能发送一个包含10封或更少电子邮件的数组。所以如果有一个20封电子邮件的原始数组,我需要把它们分成两个数组,每个10个。或者如果原始数组中有15封电子邮件,那么1个10的数组,另一个5的数组。我在使用jQuery,最好的方法是什么?

14 个解决方案

#1


116  

Don't use jquery...use plain javascript

不使用jquery……使用纯javascript

var a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];

var b = a.splice(0,10);

//a is now [11,12,13,14,15];
//b is now [1,2,3,4,5,6,7,8,9,10];

You could loop this to get the behavior you want.

你可以循环这个来得到你想要的行为。

var a = YOUR_ARRAY;
while(a.length) {
    console.log(a.splice(0,10));
}

This would give you 10 elements at a time...if you have say 15 elements, you would get 1-10, the 11-15 as you wanted.

这样你一次可以得到10个元素……如果有15个元素,就会得到1-10,11-15。

#2


65  

var size = 10;
for (var i=0; i<bigarray.length; i+=size) {
    var smallarray = bigarray.slice(i,i+size);
    // do something with smallarray
}

Unlike splice(), slice() is non-destructive to the original array.

与splice()不同,slice()对原始数组没有破坏性。

#3


23  

Just loop over the array, splicing it until it's all consumed.

只需对数组进行循环,将它拼接起来,直到它全部被消耗。



var a = ['a','b','c','d','e','f','g']
  , chunk

while (a.length > 0) {

  chunk = a.splice(0,3)

  console.log(chunk)

}

output

输出


[ 'a', 'b', 'c' ]
[ 'd', 'e', 'f' ]
[ 'g' ]

#4


18  

You can use lodash: https://lodash.com/docs

您可以使用lodash: https://lodash.com/docs

_.chunk(['a', 'b', 'c', 'd'], 2);
// → [['a', 'b'], ['c', 'd']]

#5


9  

Assuming you don't want to destroy the original array, you can use code like this to break up the long array into smaller arrays which you can then iterate over:

假设你不想破坏原来的数组,你可以用像这样的代码把长数组分解成更小的数组,然后你可以迭代:

var longArray = [];   // assume this has 100 or more email addresses in it
var shortArrays = [], i, len;

for (i = 0, len = longArray.length; i < len; i += 10) {
    shortArrays.push(longArray.slice(i, i + 10));
}

// now you can iterate over shortArrays which is an 
// array of arrays where each array has 10 or fewer 
// of the original email addresses in it

for (i = 0, len = shortArrays.length; i < len; i++) {
    // shortArrays[i] is an array of email addresss of 10 or less
}

#6


5  

As a supplement to @jyore's answer, and in case you still want to keep the original array:

作为@jyore答案的补充,如果您还想保留原始数组:

var originalArray = [1,2,3,4,5,6,7,8];

var splitArray = function (arr, size) {

  var arr2 = arr.slice(0),
      arrays = [];

  while (arr2.length > 0) {
      arrays.push(arr2.splice(0, size));
  }

  return arrays;
}

splitArray(originalArray, 2);
// originalArray is still = [1,2,3,4,5,6,7,8];

#7


3  

I would like to share my solution as well. It's a little bit more verbose but works as well.

我也想分享我的解决方案。它有点啰嗦,但也同样有效。

var data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];

var chunksize = 4;


var chunks = [];

data.forEach((item)=>{
  if(!chunks.length || chunks[chunks.length-1].length == chunksize)
  chunks.push([]);

  chunks[chunks.length-1].push(item);
});

console.log(chunks);

Output (formatted):

输出(格式):

[ [ 1,  2,  3,  4],
  [ 5,  6,  7,  8],
  [ 9, 10, 11, 12],
  [13, 14, 15    ] ]

#8


2  

Another method:

另一种方法:

var longArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var size = 2;

var newArray = new Array(Math.ceil(longArray.length / size)).fill("")
    .map(function() { return this.splice(0, size) }, longArray.slice());

// newArray = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]];

This doesn't affect the original array as a copy, made using slice, is passed into the 'this' argument of map.

这不会影响原始数组,因为使用slice生成的副本被传递到map的“This”参数中。

#9


2  

Another implementation:

另一个实现:

const arr = ["H", "o", "w", " ", "t", "o", " ", "s", "p", "l", "i", "t", " ", "a", " ", "l", "o", "n", "g", " ", "a", "r", "r", "a", "y", " ", "i", "n", "t", "o", " ", "s", "m", "a", "l", "l", "e", "r", " ", "a", "r", "r", "a", "y", "s", ",", " ", "w", "i", "t", "h", " ", "J", "a", "v", "a", "S", "c", "r", "i", "p", "t"];

const size = 3; 
const res = arr.reduce((acc, curr, i) => {
  if ( !(i % size)  ) {    // if index is 0 or can be divided by the `size`...
    acc.push(arr.slice(i, i + size));   // ..push a chunk of the original array to the accumulator
  }
  return acc;
}, []);

// => [["H", "o", "w"], [" ", "t", "o"], [" ", "s", "p"], ["l", "i", "t"], [" ", "a", " "], ["l", "o", "n"], ["g", " ", "a"], ["r", "r", "a"], ["y", " ", "i"], ["n", "t", "o"], [" ", "s", "m"], ["a", "l", "l"], ["e", "r", " "], ["a", "r", "r"], ["a", "y", "s"], [",", " ", "w"], ["i", "t", "h"], [" ", "J", "a"], ["v", "a", "S"], ["c", "r", "i"], ["p", "t"]]

NB - This does not modify the original array.

NB——这不会修改原始数组。

Or, if you prefer a functional, immutable and self-contained method:

或者,如果您喜欢一种功能性的、不可变的、自包含的方法:

function splitBy(size, list) {
  return list.reduce((acc, curr, i, self) => {
    if ( !(i % size)  ) {  
      return [
          ...acc,
          self.slice(i, i + size),
        ];
    }
    return acc;
  }, []);
}

#10


1  

You can take a look at this code . Simple and Effective .

您可以看一下这段代码。简单而有效的。

function chunkArrayInGroups(array, unit) {
var results = [],
length = Math.ceil(array.length / unit);

for (var i = 0; i < length; i++) {
    results.push(array.slice(i * unit, (i + 1) * unit));
}
 return results;
}

chunkArrayInGroups(["a", "b", "c", "d"], 2);

#11


1  

Here is a simple one liner

这是一个简单的内衬

var segment = (arr, n) => arr.reduce((r,e,i) => i%n ? (r[r.length-1].push(e), r)
                                                    : (r.push([e]), r), []),
        arr = Array.from({length: 31}).map((_,i) => i+1);
console.log(segment(arr,7));

#12


0  

If you want a method that doesn't modify the existing array, try this:

如果您想要一个不修改现有数组的方法,可以尝试以下方法:

let oldArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
let newArray = [];
let size = 3; // Size of chunks you are after
let j = 0; // This helps us keep track of the child arrays

for (var i = 0; i < oldArray.length; i++) {
  if (i % size === 0) {
    j++
  }
  if(!newArray[j]) newArray[j] = [];
  newArray[j].push(oldArray[i])
}

#13


0  

Another implementation, using Array.reduce (I think it’s the only one missing!):

另一个实现中,使用数组。减少(我想这是唯一缺失的!)

const splitArray = (arr, size) =>
{
    if (size === 0) {
        return [];
    }

    return arr.reduce((split, element, index) => {
        index % size === 0 ? split.push([element]) : split[Math.floor(index / size)].push(element);
        return split;
    }, []);
};

As many solutions above, this one’s non-destructive. Returning an empty array when the size is 0 is just a convention. If the if block is omitted you get an error, which might be what you want.

上面有很多解,这个是无损的。当大小为0时返回空数组只是一种约定。如果If块被忽略,您将得到一个错误,这可能是您想要的。

#14


0  

function chunkArrayInGroups(arr, size) {
    var newArr=[];

    for (var i=0; arr.length>size; i++){
    newArr.push(arr.splice(0,size));
    }
    newArr.push(arr.slice(0));
    return newArr;

}

chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3);

#1


116  

Don't use jquery...use plain javascript

不使用jquery……使用纯javascript

var a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];

var b = a.splice(0,10);

//a is now [11,12,13,14,15];
//b is now [1,2,3,4,5,6,7,8,9,10];

You could loop this to get the behavior you want.

你可以循环这个来得到你想要的行为。

var a = YOUR_ARRAY;
while(a.length) {
    console.log(a.splice(0,10));
}

This would give you 10 elements at a time...if you have say 15 elements, you would get 1-10, the 11-15 as you wanted.

这样你一次可以得到10个元素……如果有15个元素,就会得到1-10,11-15。

#2


65  

var size = 10;
for (var i=0; i<bigarray.length; i+=size) {
    var smallarray = bigarray.slice(i,i+size);
    // do something with smallarray
}

Unlike splice(), slice() is non-destructive to the original array.

与splice()不同,slice()对原始数组没有破坏性。

#3


23  

Just loop over the array, splicing it until it's all consumed.

只需对数组进行循环,将它拼接起来,直到它全部被消耗。



var a = ['a','b','c','d','e','f','g']
  , chunk

while (a.length > 0) {

  chunk = a.splice(0,3)

  console.log(chunk)

}

output

输出


[ 'a', 'b', 'c' ]
[ 'd', 'e', 'f' ]
[ 'g' ]

#4


18  

You can use lodash: https://lodash.com/docs

您可以使用lodash: https://lodash.com/docs

_.chunk(['a', 'b', 'c', 'd'], 2);
// → [['a', 'b'], ['c', 'd']]

#5


9  

Assuming you don't want to destroy the original array, you can use code like this to break up the long array into smaller arrays which you can then iterate over:

假设你不想破坏原来的数组,你可以用像这样的代码把长数组分解成更小的数组,然后你可以迭代:

var longArray = [];   // assume this has 100 or more email addresses in it
var shortArrays = [], i, len;

for (i = 0, len = longArray.length; i < len; i += 10) {
    shortArrays.push(longArray.slice(i, i + 10));
}

// now you can iterate over shortArrays which is an 
// array of arrays where each array has 10 or fewer 
// of the original email addresses in it

for (i = 0, len = shortArrays.length; i < len; i++) {
    // shortArrays[i] is an array of email addresss of 10 or less
}

#6


5  

As a supplement to @jyore's answer, and in case you still want to keep the original array:

作为@jyore答案的补充,如果您还想保留原始数组:

var originalArray = [1,2,3,4,5,6,7,8];

var splitArray = function (arr, size) {

  var arr2 = arr.slice(0),
      arrays = [];

  while (arr2.length > 0) {
      arrays.push(arr2.splice(0, size));
  }

  return arrays;
}

splitArray(originalArray, 2);
// originalArray is still = [1,2,3,4,5,6,7,8];

#7


3  

I would like to share my solution as well. It's a little bit more verbose but works as well.

我也想分享我的解决方案。它有点啰嗦,但也同样有效。

var data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];

var chunksize = 4;


var chunks = [];

data.forEach((item)=>{
  if(!chunks.length || chunks[chunks.length-1].length == chunksize)
  chunks.push([]);

  chunks[chunks.length-1].push(item);
});

console.log(chunks);

Output (formatted):

输出(格式):

[ [ 1,  2,  3,  4],
  [ 5,  6,  7,  8],
  [ 9, 10, 11, 12],
  [13, 14, 15    ] ]

#8


2  

Another method:

另一种方法:

var longArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var size = 2;

var newArray = new Array(Math.ceil(longArray.length / size)).fill("")
    .map(function() { return this.splice(0, size) }, longArray.slice());

// newArray = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]];

This doesn't affect the original array as a copy, made using slice, is passed into the 'this' argument of map.

这不会影响原始数组,因为使用slice生成的副本被传递到map的“This”参数中。

#9


2  

Another implementation:

另一个实现:

const arr = ["H", "o", "w", " ", "t", "o", " ", "s", "p", "l", "i", "t", " ", "a", " ", "l", "o", "n", "g", " ", "a", "r", "r", "a", "y", " ", "i", "n", "t", "o", " ", "s", "m", "a", "l", "l", "e", "r", " ", "a", "r", "r", "a", "y", "s", ",", " ", "w", "i", "t", "h", " ", "J", "a", "v", "a", "S", "c", "r", "i", "p", "t"];

const size = 3; 
const res = arr.reduce((acc, curr, i) => {
  if ( !(i % size)  ) {    // if index is 0 or can be divided by the `size`...
    acc.push(arr.slice(i, i + size));   // ..push a chunk of the original array to the accumulator
  }
  return acc;
}, []);

// => [["H", "o", "w"], [" ", "t", "o"], [" ", "s", "p"], ["l", "i", "t"], [" ", "a", " "], ["l", "o", "n"], ["g", " ", "a"], ["r", "r", "a"], ["y", " ", "i"], ["n", "t", "o"], [" ", "s", "m"], ["a", "l", "l"], ["e", "r", " "], ["a", "r", "r"], ["a", "y", "s"], [",", " ", "w"], ["i", "t", "h"], [" ", "J", "a"], ["v", "a", "S"], ["c", "r", "i"], ["p", "t"]]

NB - This does not modify the original array.

NB——这不会修改原始数组。

Or, if you prefer a functional, immutable and self-contained method:

或者,如果您喜欢一种功能性的、不可变的、自包含的方法:

function splitBy(size, list) {
  return list.reduce((acc, curr, i, self) => {
    if ( !(i % size)  ) {  
      return [
          ...acc,
          self.slice(i, i + size),
        ];
    }
    return acc;
  }, []);
}

#10


1  

You can take a look at this code . Simple and Effective .

您可以看一下这段代码。简单而有效的。

function chunkArrayInGroups(array, unit) {
var results = [],
length = Math.ceil(array.length / unit);

for (var i = 0; i < length; i++) {
    results.push(array.slice(i * unit, (i + 1) * unit));
}
 return results;
}

chunkArrayInGroups(["a", "b", "c", "d"], 2);

#11


1  

Here is a simple one liner

这是一个简单的内衬

var segment = (arr, n) => arr.reduce((r,e,i) => i%n ? (r[r.length-1].push(e), r)
                                                    : (r.push([e]), r), []),
        arr = Array.from({length: 31}).map((_,i) => i+1);
console.log(segment(arr,7));

#12


0  

If you want a method that doesn't modify the existing array, try this:

如果您想要一个不修改现有数组的方法,可以尝试以下方法:

let oldArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
let newArray = [];
let size = 3; // Size of chunks you are after
let j = 0; // This helps us keep track of the child arrays

for (var i = 0; i < oldArray.length; i++) {
  if (i % size === 0) {
    j++
  }
  if(!newArray[j]) newArray[j] = [];
  newArray[j].push(oldArray[i])
}

#13


0  

Another implementation, using Array.reduce (I think it’s the only one missing!):

另一个实现中,使用数组。减少(我想这是唯一缺失的!)

const splitArray = (arr, size) =>
{
    if (size === 0) {
        return [];
    }

    return arr.reduce((split, element, index) => {
        index % size === 0 ? split.push([element]) : split[Math.floor(index / size)].push(element);
        return split;
    }, []);
};

As many solutions above, this one’s non-destructive. Returning an empty array when the size is 0 is just a convention. If the if block is omitted you get an error, which might be what you want.

上面有很多解,这个是无损的。当大小为0时返回空数组只是一种约定。如果If块被忽略,您将得到一个错误,这可能是您想要的。

#14


0  

function chunkArrayInGroups(arr, size) {
    var newArr=[];

    for (var i=0; arr.length>size; i++){
    newArr.push(arr.splice(0,size));
    }
    newArr.push(arr.slice(0));
    return newArr;

}

chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3);