1let arr=[{id:1,title:'A', status:true}, {id:3,title:'B',status:true}, {id:2, title:'xys', status:true}];
2//find where title=B
3let x = arr.filter((a)=>{if(a.title=='B'){return a}});
4console.log(x)//[{id:3,title:'B',status:true}]
1// use filter() function. Let say we have array of object.
2let arr = [
3 {name: "John", age: 30},
4 {name: "Grin", age: 10},
5 {name: "Marie", age: 50},
6];
7//Now I want an array in which person having age more than 40 is not
8//there, i.e, I want to filter it out using age property. So
9let newArr = arr.filter((person)=>(return person.age <= 40));
10//filter function expects a function if it return true then it added
11//into new array, otherwise it is ignored. So new Array would be
12/* [
13 {name: "John", age: 30},
14 {name: "Grin", age: 10},
15 ]
16*/
1const data = [
2 {
3 name: 'Bob',
4 gender: 'male',
5 age: 34,
6 },
7 {
8 name: 'Carol',
9 gender: 'female',
10 age: 36,
11 },
12 {
13 name: 'Ted',
14 gender: 'male',
15 age: 38,
16 },
17 {
18 name: 'Alice',
19 gender: 'female',
20 age: 40,
21 },
22];
23
24const arr1 = data.filter(d => d.age > 37);
25console.log('arr1', arr1);
26
27const arr2 = data.filter(d => d.gender === 'female');
28console.log('arr2', arr2);
29
30const ageAndGender = d => d.age > 37 && d.gender === 'female';
31
32const arr3 = data.filter(ageAndGender);
33console.log('arr3', arr3);
34
1var heroes = [
2 {name: “Batman”, franchise: “DC”},
3 {name: “Ironman”, franchise: “Marvel”},
4 {name: “Thor”, franchise: “Marvel”},
5 {name: “Superman”, franchise: “DC”}
6];
7
8var marvelHeroes = heroes.filter(function(hero) {
9 return hero.franchise == “Marvel”;
10});
11
12// [ {name: “Ironman”, franchise: “Marvel”}, {name: “Thor”, franchise: “Marvel”} ]
1let people = [
2 { name: "Steve", age: 27, country: "America" },
3 { name: "Jacob", age: 24, country: "America" }
4];
5
6let filteredPeople = people.filter(function (currentElement) {
7 // the current value is an object, so you can check on its properties
8 return currentElement.country === "America" && currentElement.age < 25;
9});
10
11console.log(filteredPeople);
12// [{ name: "Jacob", age: 24, country: "America" }]
13
1function isBigEnough(value) {
2 return value >= 10
3}
4
5let filtered = [12, 5, 8, 130, 44].filter(isBigEnough)
6// filtered is [12, 130, 44]
7