13

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?

Miha Šušteršič
  • 9,742
  • 25
  • 92
  • 163
  • `.map()` would not be a good choice, because it's designed to return a 1 for 1 mapping. You could use `.reduce()` though. – Pointy Dec 24 '16 at 11:38
  • @Pointy Why would I use reduce for what is in essence a filter? –  Dec 24 '16 at 13:04
  • @torazaburo sure, that's true. I usually think of "filter" having something to do with the intrinsic nature of the values in the list, but that's I guess just my problem :) – Pointy Dec 24 '16 at 14:06

1 Answers1

16

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.

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • what does `_` mean in expression `(_, i)`? – StepUp Dec 24 '16 at 20:15
  • 1
    @StepUp That is just an unused argument, That's why we used an underscore there. There is no special meaning in that. – Rajaprabhu Aravindasamy Dec 25 '16 at 13:06
  • 1
    Using `filter` is not the best idea if your array is big, let's say 10,000 or so because you don't want to loop over 10,000 elements, just access them directly with a for loop as done in the question. – Ahmad Karim Jun 12 '19 at 08:40