object array filter code example

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
/* [
	{name: "John", age: 30},
  	{name: "Grin", age: 10},
   ]
*/

Example 2: 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 3: 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" }]

Example 4: javascript object filter

function objectFilter = (obj, predicate) => 
    Object.keys(obj)
          .filter( key => predicate(obj[key]) )
          .reduce( (res, key) => (res[key] = obj[key], res), {} );

// Example use:
var scores = {
    John: 2, Sarah: 3, Janet: 1
};

var filtered = objectFilter(scores, num => num > 1); 
console.log(filtered);

Example 5: 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]