how to filter array of objects in javascript code example

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}];
//find where title=B
let x = arr.filter((a)=>{if(a.title=='B'){return a}});
console.log(x)//[{id:3,title:'B',status:true}]

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: 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: filter array object by its elements

const things = {
  thing: [
    { place: 'here', name: 'stuff' },
    { place: 'there', name: 'morestuff1' },
    { place: 'there', name: 'morestuff2' }, 
  ],
};

const removeDuplicates = (array, key) => {
  return array.reduce((arr, item) => {
    const removed = arr.filter(i => i[key] !== item[key]);
    return [...removed, item];
  }, []);
};

console.log(removeDuplicates(things.thing, 'place'));
// > [{ place: 'here', name: 'stuff' }, { place: 'there', name: 'morestuff2' }]

Example 5: who to accses to an object vallue inside an array with .filter method js

const array = [
  {
    username: "john",
    team: "red",
    score: 5,
    items: ["ball", "book", "pen"]
  },
  {
    username: "becky",
    team: "blue",
    score: 10,
    items: ["tape", "backpack", "pen"]
  },
  {
    username: "susy",
    team: "red",
    score: 55,
    items: ["ball", "eraser", "pen"]
  },
  {
    username: "tyson",
    team: "green",
    score: 1,
    items: ["book", "pen"]
  },

];
//FILTER MEMBERS IN TEAM "RED"
const filterArray=array.filter(word=>word.team==="red")

Example 6: 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) {
  // the current value is an object, so you can check on its properties
  return currentElement.country === "America" && currentElement.age < 25;
});

console.log(filteredPeople);
// [{ name: "Jacob", age: 24, country: "America" }]