如何使用JavaScript将长数组拆分为较小的数组


98

我有一组电子邮件(可以是1封电子邮件,也可以是100封电子邮件),我需要用ajax请求发送该数组(我知道该怎么做),但是我只能发送一个包含以下内容的数组不超过10封电子邮件。因此,如果原始数组中包含20封电子邮件,我将需要将其拆分为2个数组,每组10个。或者,如果原始数组中有15封电子邮件,那么1数组中的10封电子邮件,以及另一个数组中的5封电子邮件。我使用的是jQuery,什么是最好的方法?

Answers:


194

不要使用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];

您可以循环执行此操作以获得所需的行为。

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

这一次将给您10个元素...如果您说15个元素,您将得到1-10,即您想要的11-15。


9
注意,YOUR_ARRAY也将被使用(数组是对象...)
Claudio

是的,我只是说这是因为a是非描述性的,并且我已经使用a编写了示例...这是完全不必要的代码行...尽管,这让我觉得...如果使用此模式,您可能需要对工作阵列进行深层复制,以免破坏原始图像
jyore 2011年

@junvar IDK(如果该1线在2018年起作用)(我对此表示严重怀疑),但今天却失败了。您永远都不应更改(即删除元素)要遍历的数组,它会抛弃索引,即,每次删除后,都应根据删除的元素数对其进行重新调整,因此它“向前跳过”并且不会消耗完全排列。试试看
Drew Reese

107
var size = 10; var arrayOfArrays = [];
for (var i=0; i<bigarray.length; i+=size) {
     arrayOfArrays.push(bigarray.slice(i,i+size));
}
console.log(arrayOfArrays);

与不同splice()slice()对原始数组无损。


1
此解决方案更好
Maduekwe Pedro

38

只需遍历数组,将其拼接起来,直到全部消耗完为止。



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

while (a.length > 0) {

  chunk = a.splice(0,3)

  console.log(chunk)

}

输出


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



13

假设您不想破坏原始数组,则可以使用如下代码将长数组分解为较小的数组,然后可以对其进行迭代:

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

另一个实现:

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"]]

注意:这不会修改原始阵列。

或者,如果您更喜欢功能性的,100%不可变的(尽管像上面所做的那样在原地进行变异确实没有什么坏处)和独立的方法:

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

5

作为@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];

5

Array.reduce对于大型阵列可能效率不高,尤其是使用mod运算符时。我认为一个更简洁(可能更易于阅读)的功能解决方案是这样的:

const chunkArray = (arr, size) =>
  arr.length > size
    ? [arr.slice(0, size), ...chunkArray(arr.slice(size), size)]
    : [arr];

3

另一种方法:

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

这不会影响原始数组,因为将使用slice制作的副本传递到map的“ this”参数中。


3

我也想分享我的解决方案。它有点冗长,但也可以。

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

输出(格式化):

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

2

使用Array.reduce的另一种实现(我认为这是唯一缺少的一种!):

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;
    }, []);
};

与上面的许多解决方案一样,这是无损的。当大小为0时,返回一个空数组只是一个约定。如果if省略该块,则会出现错误,这可能是您想要的。


1

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

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

1

这是一个简单的班轮

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


1

更紧凑:

const chunk = (xs, size) =>
  xs.map((_, i) =>
    (i % size === 0 ? xs.slice(i, i + size) : null)).filter(Boolean);
    
// Usage:
const sampleArray = new Array(33).fill(undefined).map((_, i) => i);

console.log(chunk(sampleArray, 5));


0

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

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

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

不要忘记使:newArr = []一个局部变量
zgthompson

仅代码答案往往会被标记,然后由于质量低劣而被删除。您能否提供一些有关如何解决原始问题的评论?
格雷厄姆

如果块大小小于输入数组大小,则此方法不起作用。
r3wt

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

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

}

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

2
欢迎使用stackoverflow。通过添加一些解释可以改善您的答案。
Simon.SA

0

作为功​​能

var arrayChunk = function (array, chunkSize) {
            var arrayOfArrays = [];

            if (array.length <= chunkSize) {
                arrayOfArrays.push(array);
            } else {
                for (var i=0; i<array.length; i+=chunkSize) {
                    arrayOfArrays.push(array.slice(i,i+chunkSize));
                }
            }
            return arrayOfArrays;
        }

使用

arrayChunk(originalArray, 10) //10 being the chunk size.

0

使用递归

let myArr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
let size = 4; //Math.sqrt(myArr.length); --> For a n x n matrix
let tempArr = [];
function createMatrix(arr, i) {
    if (arr.length !== 0) {
      if(i % size == 0) {
        tempArr.push(arr.splice(0,size))
      } 
      createMatrix(arr, i - 1)
    }
}
createMatrix(myArr, myArr.length);
console.log(tempArr);

注意:现有数组即myArr将被修改。


0

使用原型我们可以直接设置为数组类

Array.prototype.chunk = function(n) {
  if (!this.length) {
    return [];
  }
  return [this.slice(0, n)].concat(this.slice(n).chunk(n));
};
console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15].chunk(5));


0
const originalArr = [1,2,3,4,5,6,7,8,9,10,11];
const splittedArray = [];
  while (originalArr.length > 0) {
    splittedArray.push(originalArr.splice(0,range));  
  }

范围3的输出

splittedArray === [[1,2,3][4,5,6][7,8,9][10,11]]

范围4的输出

splittedArray === [[1,2,3,4][5,6,7,8][9,10,11]]

您能添加一些描述吗?
自我
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.