How to return the matching results from Array of object based on an array of input values

  • A+
Category:Languages

I have an array of objects like below

var item = [     { "name": "John", "age": 30, "city": "New York1" },     { "name": "John1", "age": 31, "city": "New York2" },     { "name": "John2", "age": 32, "city": "New York3" },     { "name": "John3", "age": 31, "city": "New York3" } ] 

What I want is to get some of the age from this array of objects which has age property value in [30,31]

So basically the input will be an array of integers like var ageArray=[30,31];

Example :

Input : [30,31]

Output : Sum of the age of the below objects

 { "name":"John", "age":30, "city":"New York1"},  { "name":"John1", "age":31, "city":"New York2"},  { "name":"John3", "age":31, "city":"New York3"} 

So here it will be

92 

I have tried to use filter for this but not sure how can i use filter with contains

What I have tried is

var result = item .filter(obj => {                     return obj.age..includes(ages);                 }) 

Can someone help me to resolve this ?

 


Use Array#reduce

const items = [ { "name":"John", "age":30, "city":"New York1"}, { "name":"John1", "age":31, "city":"New York2"}, { "name":"John2", "age":32, "city":"New York3"}, { "name":"John3", "age":31, "city":"New York3"}]   const ages = [30, 31]; const res = items.reduce((sum, {age})=>{   if(ages.includes(age)){     sum += age;   }   return sum; }, 0);  console.log(res);

Modified for names:

const items = [ { "name":"John", "age":30, "city":"New York1"}, { "name":"John1", "age":31, "city":"New York2"}, { "name":"John2", "age":32, "city":"New York3"}, { "name":"John3", "age":31, "city":"New York3"}]   const names = ["John", "john1"].map(n=>n.toLowerCase()); const res = items.reduce((sum, {name, age})=>{   if(names.includes(name.toLowerCase())){     sum += age;   }   return sum; }, 0);  console.log(res);

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: