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*/
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”} ]
1function objectFilter = (obj, predicate) =>
2 Object.keys(obj)
3 .filter( key => predicate(obj[key]) )
4 .reduce( (res, key) => (res[key] = obj[key], res), {} );
5
6// Example use:
7var scores = {
8 John: 2, Sarah: 3, Janet: 1
9};
10
11var filtered = objectFilter(scores, num => num > 1);
12console.log(filtered);
1/** filter object by key or value */
2
3/** filter object function */
4function filterObj( obj, predicate ) {
5 var result = {}, key;
6
7 for ( key in obj ) {
8 if ( obj.hasOwnProperty( key ) && predicate( key, obj[ key ] ) ) {
9 result[ key ] = obj[ key ];
10 }
11 }
12
13 return result;
14};
15
16// example
17
18// set object
19var obj = {
20 name : 'john',
21 lastName : 'smith',
22 age : 32
23}
24
25// filter out parameters using key and value
26var filteredObj = filterObj( obj, function( key, value ) {
27 return key !== 'age' && value !== 'smith'
28});
29
30// show result
31console.log( filteredObj ); // { name: "john" }
1const filterThisArray = ["a","b","c","d","e"]
2console.log(filterThisArray) // Array(5) [ "a","b","c","d","e" ]
3
4const filteredThatArray = filterThisArray.filter((item) => item!=="e")
5console.log(filteredThatArray) // Array(4) [ "a","b","c","d" ]
6