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" }
1// Our data
2const fruits = {
3 apple: {
4 qty: 300,
5 color: "green",
6 name: "apple",
7 price: 2
8 },
9 banana: {
10 qty: 130,
11 color: "yellow",
12 name: "banana",
13 price: 3
14 },
15 orange: {
16 qty: 120,
17 color: "orange",
18 name: "orange",
19 price: 1.5
20 },
21 melon: {
22 qty: 70,
23 color: "yellow",
24 name: "melon",
25 price: 5
26 }
27};
28// Now let"s create a map function
29const map = (obj, fun) =>
30 Object.entries(obj).reduce(
31 (prev, [key, value]) => ({
32 ...prev,
33 [key]: fun(key, value)
34 }),
35 {}
36 );
37// Finally let's map by color for example
38const myFruits = map(fruits, (_, fruit) => fruit.color);
39/*
40{ apple: 'green',
41 banana: 'yellow',
42 orange: 'orange',
43 melon: 'yellow' }
44/*