The Array Filter method is a quick and easy way to filter out data from an array.
const data = [1,2,3,4,5] const filteredData = data.filter((item, index, initialArray) => { if (item !== 3) return true return false }) console.log(filteredData) // output : [1,2,4,5]
Console:
The filter method does not mutate the original array, it returns a new array of filtered data without mangling the original.
In this first example, we start with a simple array filled with numbers from 1 to 5. Next, we call .filter
on the data array. Since the filter method returns a new array we set the call to a new const
called filteredData
. Once the filtering is complete, filteredData
will be the filtered dataset.
Filter works by accepting a callback function that is run on each item in the array. The callback function provides 3 arguments for us to use in our filtering, (item
, index
, initialArray
).
item
- This is the current item in the initial data set as we loop through the full array.
index
- This is the current index of the array as we loop through the full array.
initialArray
- This is the original set of data that filter was called on.
It is not required to use all 3 arguments and they can be left out if wanted
If the callback function returns false, that item is filterd out of the new array. If the callback function returns true, we keep that item for the new array.
// Lets filter this array to contain only red items const data = [ {id: 1, color: 'red'}, {id: 2, color: 'blue'}, {id: 3, color: 'red'}, {id: 4, color: 'green'} ]; const onlyReds = data.filter((item) => { if (item.color === 'red') return true; return false; }); console.log(onlyReds) // output : [{id: 1, color: 'red'}, {id:3, color: 'red'}]
Console:
We can use the filter method to filter more complex data sets as well. You simple deal with the filtering logic in your callback function.
// Lets filter out the red this time const data = [ {id: 1, color: 'red'}, {id: 2, color: 'blue'}, {id: 3, color: 'red'}, {id: 4, color: 'green'} ]; const noReds = data.filter((item) => { if (item.color !== 'red') return true; return false; }); console.log(noReds) // output : [{id: 2, color: 'blue'}, {id:4, color: 'green'}]
Console:
Now get out there and start filtering data!