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*/
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);
1let arr = [
2 {name: "John", age: 30},
3 {name: "Grin", age: 10},
4 {name: "Marie", age: 50},
5];
6
7//An array showing persons with age less than 40
8//is given by the following syntax
9
10let newArr = arr.filter(name=>name.age < 40));
11
12console.log(newArray); // => [{name: "John", age: 30}, {name: "Grin", age: 10},]