-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplitArray.js
More file actions
executable file
·84 lines (61 loc) · 1.62 KB
/
splitArray.js
File metadata and controls
executable file
·84 lines (61 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// 27. Split an Array into Chunks
// 1. Using slice() Method
{
let a = [10, 20, 30, 40, 50, 60, 70];
let chunk = 4;
let a1 = a.slice(0, chunk);
let a2 = a.slice(chunk, chunk + a.length);
console.log("Array 1 :" + a1 + "\nArray 2: " + a2);
}
// 2. Using splice() Method
{
let a = [10, 20, 30, 40, 50, 60, 70, 80];
let chunk = 2;
// Spliced arrays into 4 chunks
let a1 = a.splice(0, chunk);
let a2 = a.splice(0, chunk);
let a3 = a.splice(0, chunk);
let a4 = a.splice(0, chunk);
// Display Output
console.log("Array 1:", a1);
console.log("Array 2:", a2);
console.log("Array 3:", a3);
console.log("Array 4:", a4);
}
// 4. Using JavaScript for Loop
{
// Given array
let a = [10, 20, 30, 40, 50, 60, 70, 80];
// Size of chunk
let chunkSize = 2;
// Initialize the output array
let chunks = [];
// Loop to split array into chunks
for (let i = 0; i < a.length; i += chunkSize) {
let chunk = [];
// Iterate for the size of chunk
for (let j = i; j < i + chunkSize && j < a.length; j++) {
chunk.push(a[j]);
}
// push the chunk to output array
chunks.push(chunk);
}
// Display Output
console.log("Chunks:", chunks);
}
// 5. Using reduce() with slice() Method
{
// Given array
let a = [10, 20, 30, 40, 50, 60, 70, 80];
// Size of chunk
let chunkSize = 2;
// Split the array into chunks using reduce
let chunks = a.reduce((acc, _, index) => {
// Create chunk using array.slice()
// and push into the accumulator
acc.push(a.slice(index, index + chunkSize));
return acc;
}, []);
// Display Output
console.log("Chunks:", chunks);
}