0

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

2
  • I don't understand what your goal is exactly. Try to specify what exactly you are trying to achieve, and what you have tried so far. Commented Oct 1, 2018 at 15:02
  • 2
    So what did you try? This sounds like a "DO MY HOMEWORK FOR ME" type of question. Commented Oct 1, 2018 at 15:08

2 Answers 2

2

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; }

Sign up to request clarification or add additional context in comments.

Comments

1

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]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.