epixme
epixme

Reputation: 39

Why does filter removes index 0 from my array

I just wanted to confirm something that's bugging me.

I'm still learning javascript and did a challenge today. The challenge was to remove the value of every 2nd index.

I had to use the filter as part of the challenge and realised index2 on the code below doesn't return index 0 from the original array chopping off the value "a". So I got it to work by adding 1 to each of the indexes (index2 +1). Does it remove the 0 because filter() always returns true and 0 is seen as false? Sorry I know it's probably a simple answer and thanks to anyone for taking the time to help me.

const nums = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"];
const index = 3;

const extractEachKth=(nums, index)=>nums.filter((item,index2)=>(index2 +1)%index!==0)

expected result ["a", "b", "d", "e", "g", "h", "j"]```

Upvotes: 1

Views: 347

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386756

You could have a look to the wanted indices, add one and take the remainer of the wanted k of three.

The result is a number of either 1, 2 (both are truthy) or zero (this is falsy).

If this value is converted to boolean, you get for one and two true and for zero false.

const
    nums = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"],
    //       0    1         3    4         5    6         7  wanted indices
    //       1    2    3    4    5    6    7    8    9   10  all index + 1
    //       1    2    0    1    2    0    1    2    0    1  sum % 3
    //       *    *         *    *         *    *         *  take this truthy values
    extractEachKth = (nums, k) => nums.filter((_, index) => (index + 1) % k);


console.log(...extractEachKth(nums, 3)); ["a", "b", "d", "e", "g", "h", "j"]

Upvotes: 0

Md Sabbir Alam
Md Sabbir Alam

Reputation: 5064

This statement is wrong, filter() always returns true. Rather filter will let those values pass the filter for which we are returning true. In your case you are returning true if (index2 +1)%index!==0.

When index2 == 0, (index2 +1)%index!==0 => (0+1)%3 !== 0 => 1 !== 0 which is true. Therefore it lets the 0th item from the array to be passed through the filter.

Before when you weren't adding +1 to the index2,

When index2 == 0, index2%index!==0 => 0%3 !== 0 => 0!== 0 which is false. Therefore it filtered the 0th item and you didn't get that item.

Upvotes: 1

Related Questions