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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With