Example 1: how to filter an array of objects in javascript
let arr=[{id:1,title:'A', status:true}, {id:3,title:'B',status:true}, {id:2, title:'xys', status:true}];
let x = arr.filter((a)=>{if(a.title=='B'){return a}});
console.log(x)
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”;
});
Example 3: filtering json array in javascript
const data = [
{
name: 'Bob',
gender: 'male',
age: 34,
},
{
name: 'Carol',
gender: 'female',
age: 36,
},
{
name: 'Ted',
gender: 'male',
age: 38,
},
{
name: 'Alice',
gender: 'female',
age: 40,
},
];
const arr1 = data.filter(d => d.age > 37);
console.log('arr1', arr1);
const arr2 = data.filter(d => d.gender === 'female');
console.log('arr2', arr2);
const ageAndGender = d => d.age > 37 && d.gender === 'female';
const arr3 = data.filter(ageAndGender);
console.log('arr3', arr3);
Example 4: javascript filter array of objects
let people = [
{ name: "Steve", age: 27, country: "America" },
{ name: "Jacob", age: 24, country: "America" }
];
let filteredPeople = people.filter(function (currentElement) {
return currentElement.country === "America" && currentElement.age < 25;
});
console.log(filteredPeople);
Example 5: 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 6: javascript object filter
function objectFilter = (obj, predicate) =>
Object.keys(obj)
.filter( key => predicate(obj[key]) )
.reduce( (res, key) => (res[key] = obj[key], res), {} );
var scores = {
John: 2, Sarah: 3, Janet: 1
};
var filtered = objectFilter(scores, num => num > 1);
console.log(filtered);