Filter Method
Filtering arrays couldn't have been easier. To filter an arrays you need to use "Array.filter()" method which provide with a function to implement the filtering logic. The outcome is the new array with the filtering elements.
In our example, we have a dataset of users, some of whom have been verified while others haven’t been so. We’re required to filter and produce lists of users who have and have not been verified.
const users = [
{
name: 'John M',
isVerified: true,
},
{
name: 'Jane S',
isVerified: false,
},
{
name: 'Wanda M',
isVerified: true,
}
];
You’ll notice here two constants isVerified and notVerified. Both implement a map method which just extracts the name of the user from the individual objects.
The output at this time, displays all the names for both categories and we need to implement filtering logic to isolate names by their verification status. For this purpose, edit the isVerified and notVerified statements, implementing the filter method as shown below.
const isVerified = users.filter(({ isVerified }) => isVerified).map(({ name }) => name);
const notVerified = users.filter(({ isVerified }) => !isVerified).map(({ name }) => name);
console.log(`Is Varified : ${isVerified}`);
console.log(`Not Varified : ${notVerified}`);
Array.filter() filters out the element from the original array based on if the element is satisfying the test function. It does not modify the original array. Hence it is an array accessor method.
const numbers = [1, 2, 3, 4, 5]
const numbersGreaterThan2 = numbers.filter(number => number > 2)
console.log("ex 3:", numbers);
console.log("ex 3:", numbersGreaterThan2);
Array.filter() method filters out the elements according to the callback function supplied to it and returns the elements into a new array. However, since it is an accessor method, it does not modify the original array
Comments
Post a Comment