2

I have an array I want to increment over every other element. The 2nd element is always a repeat and I only want to process the first element. How can I get the map() method to increment by two and skip over one element?

let newArr = oldArr.map((item, i) => {
  // process oldArr[0] item
  // skips over oldArr[1] item
  //...
});
David Lin
  • 47
  • 4
  • You could check for `i` to be even, or use a standard loop. `map` isn't necessarily the right tool here if you don't want to process every element. – Carcigenicate Nov 28 '18 at 21:42
  • If you `return false` from within the `map` callback it will skip that item. Combine that with what Carcigenicate said above and you've got a solution. – Ding Nov 28 '18 at 21:43

1 Answers1

4

You can use .filter to skip every second value:

let oldArr = [1,1,2,2,3,3,4,4,5,5];

let newArr = oldArr.filter((v,i) => i % 2).map((item, i) => {
  console.log(item);
});
Zze
  • 18,229
  • 13
  • 85
  • 118
  • 1
    Use the implicit return of arrow functions: `oldArr.filter((v,i) => i % 2)`, BTW, he is trying to skip the items whose `i % 2` is `1` so change to `oldArr.filter((v,i) => i % 2 === 0)` – ibrahim mahrir Nov 28 '18 at 21:44