Example 1: how to filter object in javascript
// use filter() function. Let say we have array of object.
let arr = [
{name: "John", age: 30},
{name: "Grin", age: 10},
{name: "Marie", age: 50},
];
//Now I want an array in which person having age more than 40 is not
//there, i.e, I want to filter it out using age property. So
let newArr = arr.filter((person)=>(return person.age <= 40));
//filter function expects a function if it return true then it added
//into new array, otherwise it is ignored. So new Array would be
Example 2: js filter array of objects by value
var heroes = [
{name: “Batman”, franchise: “DC”},
{name: “Ironman”, franchise: “Marvel”},
{name: “Thor”, franchise: “Marvel”},
{name: “Superman”, franchise: “DC”}
];
var marvelHeroes = heroes.filter(function(hero) {
return hero.franchise == “Marvel”;
});
// [ {name: “Ironman”, franchise: “Marvel”}, {name: “Thor”, franchise: “Marvel”} ]
Example 3: javascript filter array of objects by array
var arr = [1,2,3,4],
brr = [2,4],
res = arr.filter(f => !brr.includes(f));
console.log(res);
Example 4: javascript filter array of objects
function isBigEnough(value) {
return value >= 10
}
let filtered = [12, 5, 8, 130, 44].filter(isBigEnough)
// filtered is [12, 130, 44]
Example 5: js filter object of objects
// Our data
const fruits = {
apple: {
qty: 300,
color: "green",
name: "apple",
price: 2
},
banana: {
qty: 130,
color: "yellow",
name: "banana",
price: 3
},
orange: {
qty: 120,
color: "orange",
name: "orange",
price: 1.5
},
melon: {
qty: 70,
color: "yellow",
name: "melon",
price: 5
}
};
// Now let"s create a map function
const map = (obj, fun) =>
Object.entries(obj).reduce(
(prev, [key, value]) => ({
...prev,
[key]: fun(key, value)
}),
{}
);
// Finally let's map by color for example
const myFruits = map(fruits, (_, fruit) => fruit.color);
/*
{ apple: 'green',
banana: 'yellow',
orange: 'orange',
melon: 'yellow' }
/*