Kamil Kmita
Kamil Kmita

Reputation: 35

Create new arrays in a specific order with javascript

How can i get arrays with elements of base array order like this with JS :

baseArray = [1,2,3,4,5,6,7,8]

newArray1 = [1,4,7]
newArray2 = [2,5,8]
newArray3 = [3,6]

What is the best way

Upvotes: 0

Views: 117

Answers (2)

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6749

you could try either filtering

newArray1 = baseArray.filter(function(value, index, Arr) {
    return index % 3 == 0;
});

newArray2 = baseArray.filter(function(value, index, Arr) {
    return index % 3 == 1;
});

newArray3 = baseArray.filter(function(value, index, Arr) {
    return index % 3 == 2;
});

or directly accesing array elements

let newArray1 = [];
let newArray2 = [];
let newArray3 = [];

for (let i=0; i<baseArray.length; j++){
    if (i%3==0) newArray1.push(baseArray[i]);
    if (i%3==1) newArray2.push(baseArray[i]);
    if (i%3==2) newArray3.push(baseArray[i]);
}

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386720

You could take the power of the reminder operator % for getting the right index and the target array.

var array = [1, 2, 3, 4, 5, 6, 7, 8],
    array1 = [], array2 = [], array3 = [];

array.reduce((r, v, i) => (r[i % 3].push(v), r), [array1, array2, array3]);
    
console.log(array1);
console.log(array2);
console.log(array3);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

Related Questions