Array Filter Object Javascript 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: 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 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" }

Example 5: array filter

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];  const result = words.filter(word => word.length > 6);  console.log(result); // expected output: Array ["exuberant", "destruction", "present"]

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

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?