[javascript] JavaScript를 사용하여 긴 배열을 더 작은 배열로 분할하는 방법

전자 메일 배열이 있고 (단지 1 개 또는 100 개일 수 있음) ajax 요청 (방법을 알고 있음)과 함께 배열을 보내야하지만 다음이있는 배열 만 보낼 수 있습니다. 10 개 이하의 이메일이 있습니다. 따라서 원래 20 개의 전자 메일 배열이있는 경우 각각 10 개씩 2 개의 배열로 분할해야합니다. 또는 원래 배열에 15 개의 전자 메일이 있고 10 개의 배열과 5 개의 다른 배열이있는 경우 jQuery를 사용하고 있습니다.이 작업을 수행하는 가장 좋은 방법은 무엇입니까?



답변

jquery를 사용하지 마십시오 … 일반 자바 스크립트를 사용하십시오.

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 개를 얻을 수 있습니다.


답변

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


답변

lodash를 사용할 수 있습니다 :
https://lodash.com/docs

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


답변

원래 배열을 파괴하고 싶지 않다고 가정하면 다음과 같은 코드를 사용하여 긴 배열을 더 작은 배열로 나눈 다음 반복 할 수 있습니다.

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
}


답변

또 다른 구현 :

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-이것은 원래 어레이를 수정하지 않습니다.

또는 기능적이고 100 % 불변 (위와 같이 변경하는 것이 나쁘지는 않지만)과 자체 포함 된 방법을 선호한다면 :

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


답변

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