js object array filter 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: filter out arrays js

let newArray = array.filter(function(item) {
  return condition;
});

Example 3: 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' }
/*