The filter is one of the methods of arrays that were added in ES5.
- The filter aims to iterate over an array and filter the values to create a new array.
- The function passed into the filter method determines which values are filtered out and which are assigned to the new array.
- So the filter is a higher-order function. It accepts a function as a parameter.
- The main Application is to remove duplicate values from an array.
Definition and Usage
filter()method creates an array filled with elements that pass a test (provided by a function).
filter()does not execute the function for empty array elements.
filter()does not change the original array.
filter()method takes a callback function that has three arguments.
- The item value
- The item index
- The array itself
array.filter(function(currentValue, index, arr), thisValue)
- The first parameter is the value in the array so that the filter will iterate over every single value in this array.
- We also have a second variable here. This allows us to grab the index position of the element.
- We take the array, and we do the
indexofthat returns the index position of this value, so whatever value is passed in, we want to get the index position of it.
let array = [ 1, 2, 3, 4, 2, 5, 4, 1, 5, 6 ] let newArray = array.filter((num,i) => array.indexOf(num) === i);
As mentioned, a filter is a method of arrays, so we specify the array
(arr.filter) filter that’s how we access.
It’s a higher-order function, so we pass in a function right here.
We give in a function as the parameter, which is used to filter out particular values now.
The function that is passed in can take several parameters.
["foo", "bar", "baz"].filter(item => item.startsWith("ba")) // returns ["bar", "baz"];
That’s how it’s removing duplicates.
filter()is fully supported in all modern browsers