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”} ]
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/*