Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take every 3rd element of an array [duplicate]

I have an array, and want to return only every third element as a new array (starting at 0).

For example:

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let newArr = [1, 4, 7];

This is the way I am currently doing this:

let newArr = [];
for(let x = 0; x < arr.length; x += 3) {
   newArr.push(arr[x]);
}
return newArr;

Is there a way to do this with arr.map? Is there just an easier way to do this?

like image 245
Miha Šušteršič Avatar asked Dec 24 '16 11:12

Miha Šušteršič


1 Answers

You can alternatively do it with a filter,

let newArr = arr.filter((_,i) => i % 3 == 0); 

But remember, using basic for loop is bit more efficient than others in some contexts.

like image 116
Rajaprabhu Aravindasamy Avatar answered Oct 28 '22 15:10

Rajaprabhu Aravindasamy