Array.filter()
is one of the built-in methods available for arrays that takes in an array and creates a new array containing data based on a criteria.
Structure
const newArray = originalArray.filter((nameOfParam) => {
return nameOfCondition;
});
Using ES5 syntax:
var newArray = originalArray.filter(function(nameOfParam){
return nameOfCondition;
});
Examples
Return the name of a fruit that has greater than 6 characters
const fruits = ['apple', 'orange', 'bananas', 'grapes'];
const filteredFruit = fruits.filter((fruit) => {
return fruit.length > 6;
});
console.log(filteredFruit); // ['bananas']
Return the names and positions of users in a certain department
const users = [
{name: 'Tom Smith', position: 'Senior Engineer', department: 'IT'},
{name: 'Danielle Layton', position: 'Head of Marketing', department: 'Marketing'},
{name: 'Peter Jacobsen', position: 'IT Manager', department: 'IT'},
{name: 'Laura Johnson', position: 'Senior Sales Representative', department: 'Sales'},
{name: 'Jessica Jones', position: 'Intermediate Software Engineer', department: 'IT'}
];
const listUsersFromDepartment = users.filter((usersInDept) => {
return usersInDept.department === 'IT';
});
console.log(listUsersFromDepartment); //[
{ name: 'Tom Smith', position: 'Senior Engineer', department: 'IT' },
{ name: 'Peter Jacobsen', position: 'IT Manager', department: 'IT' },
{ name: 'Jessica Jones', position: 'Intermediate Software Engineer', department: 'IT'}
]