Your outer loop, which loops i from 0 to indices.length
, should produce exactly one array in the result per iteration. Because you want to transform each number to one array - it's a one to one mapping.
By putting arrIndices.push(a);
inside the inner loop, you ensure that it runs many more times. So the result will have many more arrays than just one per number.
All you need to do is build the result array using the inner loop, then push it after the inner loop is done.
Also, a = a.concat(indices[i])
will only push the original number (3, 5, or 9) over and over, not anything else like 0, 1, 2, etc. For that just use j
itself.
Finally, since you want it to be inclusive, you should have j <= indices[i]
so it will loop up to and including indices[i]
.
let indices = [3,5,9];
let arrIndices = [];
for (let i = 0; i < indices.length; i++) {
console.log("k", indices[i]);
let a = [];
for (let j = 0; j <= indices[i]; j++) {
console.log("jj", j);
a.push(j);
}
arrIndices.push(a);
}
console.log(arrIndices);
However JavaScript has several array helpers and they can make this code very short. Remember how I said this is a one to one mapping? Javascript has a helper for that - Array#map
. There is also a shortcut to making an array of 0..N from this answer using the Array constructor and Array#keys()
method.
let indices = [3,5,9];
let result = indices.map(n => [...Array(n+1).keys()]);
console.log(result);