Reputation: 71
I want to split an array in jquery so that after splitting, the last element for previous array should be the first element of current array.
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
If I do splice
then it will splice exactly same size and next array will be next element. so if I am splicing it into 5 my output should be
var firstArr = arr.splice[0,4];
var secondArr = arr.splice[0,4];
var thirdArr = arr.splice[0,4];
var fourthArr = arr.splice[0,4];
var fifthArr = arr.splice[0,4];
Right now I am getting
[1,2,3,4]
[5,6,7,8]
...
What I need is
//firstArr = [1,2,3,4];
//secondArr = [4,5,6,7];
//thirdArr = [7,8,9,10];
//fourthArr = [10,11,12,13];
//fifthArr = [13,14,15,16];
How to achieve this in jQuery ?
Upvotes: 1
Views: 412
Reputation: 2822
const chunk = (a1, s) => {
const a2 = [];
let i = k = j = 0;
while (s > 1 && a1[i - k]) {
j = i % s;
k = (i - j) / s
a2[k] ??= [];
a2[k][j] = a1[i - k];
i++;
}
return a2;
}
console.log(chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], 4));
console.log(chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], 7));
console.log(chunk([1, 2, 3, 4, 5, 6, 7, 8, 9], 3));
console.log(chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3));
console.log(chunk([1, 2, 3], 8));
console.log(chunk([], 10));
console.log(chunk([1, 2, 3, 4], 0));
console.log(chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'], 4));
Upvotes: 0
Reputation: 19319
I don't know a jquery array function that is preferable to using a plain javascript solution. Below is an example that generically handles your requirement by:
ceil
of: the length of input array plus the floor
number of duplicated entries, all divided by the size of the output chunkslice
such that the last element for previous array is the first element of current array.// chunking function
function chunk(arr, size) {
if (size === 0) return [];
var arrCount = Math.ceil((arr.length + Math.floor(arr.length / size)) / size);
var chunks = [];
for (let i=0; i<arrCount; ++i) {
chunks.push(arr.slice(i * (size - 1), i * (size - 1) + size));
}
return chunks;
}
// tests
console.log(chunk([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16], 4));
console.log(chunk([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16], 7));
console.log(chunk([1,2,3,4,5,6,7,8,9], 3));
console.log(chunk([1,2,3,4,5,6,7,8,9,10], 3));
console.log(chunk([1,2,3], 8));
console.log(chunk([], 10));
console.log(chunk([1, 2, 3, 4], 0));
console.log(chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'], 4));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 2
Reputation: 19
const arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
let slices = []
let start = 0
let end = 3
for(i = 0; i < 5; i++){
let slice = arr.slice(start,end)
slice.push(arr[end])
start += 3
end += 3
slices.push(slice)
}
Upvotes: 0