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

时间:2011-09-01 16:52:27

标签: javascript jquery arrays loops

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

21 个答案:

答案 0 :(得分:139)

不要使用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个。

答案 1 :(得分:76)

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()对原始数组无破坏性。

答案 2 :(得分:26)

只需循环遍历数组,拼接它直到它全部耗尽。



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

答案 3 :(得分:25)

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

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

答案 4 :(得分:9)

假设您不想破坏原始数组,可以使用这样的代码将长数组分解为更小的数组,然后可以迭代:

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
}

答案 5 :(得分:5)

作为@ jyore的answer的补充,如果您仍想保留原始数组:

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

答案 6 :(得分: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    ] ]

答案 7 :(得分:3)

另一种实施方式:

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

注意 - 这不会修改原始数组。

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

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

答案 8 :(得分: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]];

这不会影响原始数组,因为使用切片制作的副本会传递到&#39;这个&#39;地图的论点。

答案 9 :(得分:1)

另一个实现,使用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块,则会出现错误,这可能是您想要的。

答案 10 :(得分:1)

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

MonthNumber

答案 11 :(得分:1)

这是一个简单的单线

&#13;
&#13;
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));
&#13;
&#13;
&#13;

答案 12 :(得分: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);

答案 13 :(得分: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])
}

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

答案 15 :(得分:0)

更紧凑:

decimal? numValue = numericUpDown1?.Value;

答案 16 :(得分:0)

Dim ws as Worksheet: Set ws = ThisWorkbook.Sheets("working")

Set r = ws.Range(ws.Cells(1, 1), ws.Cells(4, 2))

答案 17 :(得分: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.

答案 18 :(得分: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将被修改。

答案 19 :(得分: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));

答案 20 :(得分: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]]