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

/** filter object by key or value */

/** filter object function */
function filterObj( obj, predicate ) {
	var result = {}, key;

	for ( key in obj ) {
		if ( obj.hasOwnProperty( key ) && predicate( key, obj[ key ] ) ) {
			result[ key ] = obj[ key ];
		}
	}

	return result;
};

// example

// set object
var obj = {
	name : 'john',
	lastName : 'smith',
	age : 32
}

// filter out parameters using key and value
var filteredObj = filterObj( obj, function( key, value ) {
	return key !== 'age' && value !== 'smith'
});

// show result
console.log( filteredObj ); // { name: "john" }