3 Neat Tricks Using the Filter Method

Photo by Blake Richard Verdoorn on Unsplash

When we have a long list of items in an array. We don’t need all that information, we only want a certain type item. We can use the filter method to filter out the unwanted data. If nothing matches the condition, we get back an empty array.

The Array.prototype.filter() method takes in a callback, which accepts 3 arguments ==> currentValue, index, array.


1. Return all Unique Numbers

const nums = [4,4,1,2,8,1,2,4,4]let uniq = nums.filter((v,i,a) => {
return a.indexOf(v) === i

// [4,1,2,8]

The third argument in the filter a is the same array as nums .

indexOf() will find the index of the first occurrence of the given argument. It goes from 0 to the last index of the array.

a.indexOf(4) has to equal Index 0
a.indexOf(1) has to equal Index 2
a.indexOf(2) has to equal Index 3
a.indexOf(8) has to equal Index 4

The 4 at Index 0 meets the condition. Is the first occurrence in the array so it gets returned.

The second 4 at Index 1. It doesn’t meet the condition. Index 1 doesn’t equal Index 0

2. Return all the Numbers that occurs 2 or more times

const nums = [4,4,1,2,8,1,2,4,4]let occurMultiple = nums.filter((v,i,a) => {
return a.indexOf(v) !== i && a.lastIndexOf(v) === i
// [1,2,4]

lastIndexOf() will find the index of the last occurrence of the given argument. Or first occurrence if it goes from last index to 0 of the array.

If the lastIndexOf() exist AND doesn’t equal the indexOf(), therefore the value occurs at least 2 times in the array.

The following value at index meets the filter condition
1 at index 5
2 at index 6
4 at index 8

3. Return all Numbers that occurs ONLY 1 time

const nums = [4,4,1,2,8,1,2,4,4]

let occurOnce= nums.filter((v,i,a) => {
return a.indexOf(v) === i && a.lastIndexOf(v) === i
// [8]

When both the indexOf() and the lastIndexOf() points to the same index, therefore that is the only value that occurred in the array.

a.indexOf(8) equal Index 4
a.lastIndexOf(8) equal Index 4

Copy and Paste what’s on my mind. Perfect.