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

发布于 2024-12-02 15:49:19 字数 236 浏览 3 评论 0原文

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(27

╄→承喏 2024-12-09 15:49:20

作为一个函数

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.

as a function

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

to use

arrayChunk(originalArray, 10) //10 being the chunk size.
很酷不放纵 2024-12-09 15:49:20

使用递归

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 将被修改。

using recursion

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

Note: The existing array i.e. myArr will be modified.

悲歌长辞 2024-12-09 15:49:20

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

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

using prototype we can set directly to array class

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

土豪 2024-12-09 15:49:20
let original = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
let size = 5;
let fragments = Array.from(Array(Math.ceil(a.length / size))).map((_,index) => a.slice(index * size,(index + 1) * size))
let original = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
let size = 5;
let fragments = Array.from(Array(Math.ceil(a.length / size))).map((_,index) => a.slice(index * size,(index + 1) * size))
り繁华旳梦境 2024-12-09 15:49:20

如果您知道要拆分的数字数组 (numGroups),则可以使用以下函数。

function createGroups(arr, numGroups) {
    const perGroup = Math.ceil(arr.length / numGroups);
    return new Array(numGroups)
        .fill('')
        .map((_, i) => arr.slice(i * perGroup, (i + 1) * perGroup));
}

示例使用:

createGroups([0, 1, 2, 3, 4, 5, 6], 3); //arr = [0, 1, 2, 3, 4, 5, 6] and numGroups = 3

You can use the below function if you know the number array (numGroups) to be split.

function createGroups(arr, numGroups) {
    const perGroup = Math.ceil(arr.length / numGroups);
    return new Array(numGroups)
        .fill('')
        .map((_, i) => arr.slice(i * perGroup, (i + 1) * perGroup));
}

Sample Use:

createGroups([0, 1, 2, 3, 4, 5, 6], 3); //arr = [0, 1, 2, 3, 4, 5, 6] and numGroups = 3
迷爱 2024-12-09 15:49:20

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

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

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])
}
挥剑断情 2024-12-09 15:49:20
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);
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);
机场等船 2024-12-09 15:49:20

您可以使用以下代码来实现所需的功能

const splitter = (arr, splitBy, cache = []) => {
        const tmp = [...arr]
        while (tmp.length) cache.push(tmp.splice(0, splitBy))
        return cache
}
const split = splitter([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21], 10)
console.log(split); 

请注意,它是一个长度为 22 的数组,然后 splitter 函数将其拆分为 2 个包含 10 个项目的较小数组和 1 个包含 2 个项目的数组。

You can use the following code to achieve the required functionality

const splitter = (arr, splitBy, cache = []) => {
        const tmp = [...arr]
        while (tmp.length) cache.push(tmp.splice(0, splitBy))
        return cache
}
const split = splitter([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21], 10)
console.log(split); 

Notice, it was an array of length 22 then the splitter function splits it into 2 smaller arrays of 10 items and 1 array of 2 items.

只涨不跌 2024-12-09 15:49:20
let a = [1, 2, 3, 4, 6, 7, 8, 9, 10, 11];
let _splitCount = 3;

let b = a.reduce((acc, curr, index) => {
  if (index % _splitCount === 0) {
    acc.push([curr]);
  } else {
    acc[acc.length - 1].push(curr);
  }
  return acc;
}, []);

这是我认为简单的解决方案❤️

let a = [1, 2, 3, 4, 6, 7, 8, 9, 10, 11];
let _splitCount = 3;

let b = a.reduce((acc, curr, index) => {
  if (index % _splitCount === 0) {
    acc.push([curr]);
  } else {
    acc[acc.length - 1].push(curr);
  }
  return acc;
}, []);

this is the easy solution i think❤️

情未る 2024-12-09 15:49:20

您可以使用 map+filter 作为减少的替代方案:

a.map((x,i,a,chunk=3)=>i%chunk ? null: a.slice(i,i+chunk)).filter(x=>x) 

You could use map+filter as an alternative to reduce:

a.map((x,i,a,chunk=3)=>i%chunk ? null: a.slice(i,i+chunk)).filter(x=>x) 
╭⌒浅淡时光〆 2024-12-09 15:49:19

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

Don't use jquery...use plain 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.

浮生面具三千个 2024-12-09 15:49:19
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() 对原始数组是无损的。

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

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

魔法唧唧 2024-12-09 15:49:19

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

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

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

_.chunk(['a', 'b', 'c', 'd'], 2);
// → [['a', 'b'], ['c', 'd']]
梦境 2024-12-09 15:49:19

只需循环数组,拼接它,直到全部消耗完。



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

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

浪漫之都 2024-12-09 15:49:19

Array.reduce 对于大型数组可能效率低下,尤其是使用 mod 运算符时。我认为更清晰(并且可能更容易阅读)的功能解决方案是这样的:

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

Array.reduce could be inefficient for large arrays, especially with the mod operator. I think a cleaner (and possibly easier to read) functional solution would be this:

const chunkArray = (arr, size) =>
  arr.length > size
    ? [arr.slice(0, size), ...chunkArray(arr.slice(size), size)]
    : [arr];
枕梦 2024-12-09 15:49:19

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

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
}

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
}
余生再见 2024-12-09 15:49:19

使用 ES6 生成器

虽然姗姗来迟,但 ES6 生成器 开辟了另一种巧妙的方法达到所要求的。

/**
 * Returns chunks of size n.
 * @param {Array<any>} array any array
 * @param {number} n size of chunk 
 */
function* chunks(array, n){
  for(let i = 0; i < array.length; i += n) yield array.slice(i, i + n);
}

const result = [...chunks([1, 2, 3, 4, 5, 6, 7, 8 , 9, 10], 3)];
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

使其适用于无限生成器

使用相同的想法,您可以创建一个生成器,它还可以根据从另一个(可能是无限的)生成器函数检索的值生成无限数量的 n 大小的块。一旦需要,这对于延迟生成值来说非常方便,这会显着减少所需的内存,甚至可以用于生成可能无限/未知数量的块。

这是一个使用两个生成器的示例。

  • nextNaturalNumber() 是一个无限生成器,它始终返回下一个自然数。我在这里使用 ES2020 bigint 数据类型,因此没有对值大小的限制(通过 JavaScript)。
  • chunksFromIterable() 从可能无限的可迭代对象中创建 n 大小的块。
/**
 * Returns chunks of size n for a possibly infinite iterator.
 * n must be >= 1
 * @param {Iterable<any>} iterable any array
 * @param {number} n size of chunk for n >= 1
 */
 function* chunksFromIterable(iterable, n){
  let arr = [];
  let i = n;
  for (const value of iterable) {
    if(i <= 0) {
      // another chunk of size n is filled => return chunk
      yield arr;
      arr = []; // create new empty array
      i = n; 
    };
    arr.push(value);
    i--;
  }
  // in case the iterable is not infinite check if there are still values in the array and return them if necessary
  if(arr.length > 0) yield arr;
}

/**
 * Infinite iterator which always gets the next natural number.
 */
function* nextNaturalNumber(){
  let i = 0n;
  while(true) {
    i += 1n;
    yield i;
  }
}

console.log("Finite iterable:");
// this version can now be used using the for ... of loop
for(const threeNaturalNumbers of chunksFromIterable([1, 2, 3, 4, 5, 6, 7, 8 , 9, 10], 3)){
  console.log(threeNaturalNumbers);
}

console.log("Infinite iterable:");
// and it can also be used for this infinite generator
for(const threeNaturalNumbers of chunksFromIterable(nextNaturalNumber(), 3)){
  printBigIntArray(threeNaturalNumbers);
  if(threeNaturalNumbers[0] > 30) break; // end here to avoid an infinite loop
}

// helper function to print array of bigints as this does not seem to be working for snippets
function printBigIntArray(arr){
  console.log(`[${arr.join(", ")}]`);
}
.as-console-wrapper { max-height: 100% !important; top: 0; }

Using ES6 Generators

Late to the party, but ES6 generators opened up another neat way to achieve what is asked for.

/**
 * Returns chunks of size n.
 * @param {Array<any>} array any array
 * @param {number} n size of chunk 
 */
function* chunks(array, n){
  for(let i = 0; i < array.length; i += n) yield array.slice(i, i + n);
}

const result = [...chunks([1, 2, 3, 4, 5, 6, 7, 8 , 9, 10], 3)];
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Make it work for infinite Generators

Using the same idea you can create a generator which can also generate an infinite amount of n-sized chunks from values retrieved from another (possibly infinite) generator function. This can be very handy to lazy-generate values once they are required which significantly reduces the required memory or it can even be used to generate a possibly infinite/ unknown number of chunks.

Here an example which uses two generators.

  • nextNaturalNumber() is an infinite generator which always returns the next natural number. I am using the ES2020 bigint datatype here so there is no restriction (by JavaScript) for the size of the value.
  • chunksFromIterable() creates n-sized chunks from an possibly infinite iterable.

/**
 * Returns chunks of size n for a possibly infinite iterator.
 * n must be >= 1
 * @param {Iterable<any>} iterable any array
 * @param {number} n size of chunk for n >= 1
 */
 function* chunksFromIterable(iterable, n){
  let arr = [];
  let i = n;
  for (const value of iterable) {
    if(i <= 0) {
      // another chunk of size n is filled => return chunk
      yield arr;
      arr = []; // create new empty array
      i = n; 
    };
    arr.push(value);
    i--;
  }
  // in case the iterable is not infinite check if there are still values in the array and return them if necessary
  if(arr.length > 0) yield arr;
}

/**
 * Infinite iterator which always gets the next natural number.
 */
function* nextNaturalNumber(){
  let i = 0n;
  while(true) {
    i += 1n;
    yield i;
  }
}

console.log("Finite iterable:");
// this version can now be used using the for ... of loop
for(const threeNaturalNumbers of chunksFromIterable([1, 2, 3, 4, 5, 6, 7, 8 , 9, 10], 3)){
  console.log(threeNaturalNumbers);
}

console.log("Infinite iterable:");
// and it can also be used for this infinite generator
for(const threeNaturalNumbers of chunksFromIterable(nextNaturalNumber(), 3)){
  printBigIntArray(threeNaturalNumbers);
  if(threeNaturalNumbers[0] > 30) break; // end here to avoid an infinite loop
}

// helper function to print array of bigints as this does not seem to be working for snippets
function printBigIntArray(arr){
  console.log(`[${arr.join(", ")}]`);
}
.as-console-wrapper { max-height: 100% !important; top: 0; }

倾听心声的旋律 2024-12-09 15:49:19

另一种实现:

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

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.

Or, if you prefer a functional, 100% immutable (although there's really nothing bad in mutating in place like done above) 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;
  }, []);
}
爱冒险 2024-12-09 15:49:19

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

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

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];
原野 2024-12-09 15:49:19

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

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

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    ] ]
许仙没带伞 2024-12-09 15:49:19

您可以从一个空数组开始,然后将原始数组中包含所需范围的部分推入其中,同时从原始数组中减去,直到为空。

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

如果需要的话,这也适用于前置分页。

You can start with an empty array and push inside it sections with your desired range from the original array at the same time you are subtracting from your original array until is empty.

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

output for range 3

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

output for range 4

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

This is also good for a fronted pagination if want.

苍风燃霜 2024-12-09 15:49:19

另一种方法:

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”参数中。

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.

[旋木] 2024-12-09 15:49:19

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

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.

七分※倦醒 2024-12-09 15:49:19

更紧凑:

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

More compact:

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

幽蝶幻影 2024-12-09 15:49:19
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);
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);
ら栖息 2024-12-09 15:49:19

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

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

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);
西瑶 2024-12-09 15:49:19

这是一个简单的衬里

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文