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
}
@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];
다른 방법 :
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'인수로 전달되므로 원본 배열에는 영향을주지 않습니다.
또 다른 구현 :
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-이것은 원래 어레이를 수정하지 않습니다.
또는 기능적이고 변경 불가능하며 독립적 인 방법을 선호하는 경우 :
function splitBy(size, list) {
return list.reduce((acc, curr, i, self) => {
if ( !(i % size) ) {
return [
...acc,
self.slice(i, i + size),
];
}
return acc;
}, []);
}
내 솔루션도 공유하고 싶습니다. 좀 더 장황하지만 잘 작동합니다.
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 ] ]
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.
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);
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));
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];
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])
}
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);
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));
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);
'program story' 카테고리의 다른 글
| WPF-표준 단추를 사용하여 위쪽 및 아래쪽 화살표가있는 단추 만들기 (0) | 2020.11.09 |
|---|---|
| didReceiveRemoteNotification : fetchCompletionHandler의 구문 분석 경고 (0) | 2020.11.09 |
| Android에서 클래스 파일에서 프로그래밍 방식으로 탐색 서랍 헤더 이미지와 이름을 설정하는 방법은 무엇입니까? (0) | 2020.11.09 |
| jQueryUI 모달 대화 상자에 닫기 버튼 (x)이 표시되지 않음 (0) | 2020.11.09 |
| PHP에서 다차원 배열 전치 (0) | 2020.11.09 |