Reputation: 1337
I want to put each iteration into an array which is in a main array.
Like this: array = [[a,b], [c,d], [e,f]]
push method and slice, splice
var descendants = [A,C,C,D,C,B],
chunk = 2,
descendantPairs = [];
for (var i = 0; i < descendants.length; i += chunk) {
descendantPairs = descendantPairs.push(descendants.slice(i, i + chunk));
console.log("descendantPairs: " + descendantPairs});
}
Right now I'm able to get the pairs like this but I need to do more logic on ALL the pairs, instead of just the last pair, therefore I need an array which holds all the pairs.
I get this now in console.log:
descendantPairs: A,C
descendantPairs: C,D
descendantPairs: C,B
Upvotes: 1
Views: 1245
Reputation: 37755
You can use a simple for loop and a temp
variable and push values on every second index to final output
var arr = [`A`,`C`,`C`,`D`,`C`,`B`]
let op = []
let temp = []
for(let i = 0; i < arr.length; i++){
temp.push(arr[i])
if( i % 2 == 1 ){
op.push(temp)
temp = []
}
}
if( temp.length > 0 ){
op.push(temp)
}
console.log(op)
Upvotes: 1
Reputation: 1073
var arr = ['A','C','C','D','C','B'];
let chunk = 2;
let pairs = [];
for(let i = 0; i < arr.length; i+= chunk) {
pairs.push(arr.slice(i, i + chunk));
}
console.log(pairs);
Upvotes: -1
Reputation: 386578
You could push each slice to the result array, without assining the new length of the array. The next loop throws an error, because your descendantPairs
is now a number and not anymore an array, which is needed for using the push
method.
var descendants = ['A', 'C', 'C', 'D', 'C', 'B'],
chunk = 2,
result = [],
i = 0;
while (i < descendants.length) {
result.push(descendants.slice(i, i += chunk));
}
console.log(result);
Upvotes: 1
Reputation: 4557
Something like this will do the trick:
let descendants = ['A', 'C', 'C', 'D', 'C', 'B'];
let chunk = 2;
let result = [];
for (let i = 0; i < descendants.length; i += chunk) {
result.push(descendants.slice(i, i+chunk));
}
console.log(result);
Upvotes: 1
Reputation: 115222
Your code contains one issue, you are reassigning descendantPairs
with returned value of Array#push
method which will be the length of the array and it leads to throwing an error on the next iteration(since there is no push method for type Number
).
To make it work just remove the reassigning part and log the value after the for loop.
var descendants = ['A', 'C', 'C', 'D', 'C', 'B'],
chunk = 2,
descendantPairs = [];
for (var i = 0; i < descendants.length; i += chunk) {
descendantPairs.push(descendants.slice(i, i + chunk));
}
console.log("descendantPairs: ", descendantPairs);
Upvotes: 1
Reputation: 609
The push method returns the length of the added element, not the array after pushing the element.
replace descendantPairs = descendantPairs.push(descendants.slice(i, i + chunk));
with
descendantPairs.push(descendants.slice(i, i + chunk));
Upvotes: 2