Reputation: 9
I am trying to get the count of occurrences in the below object.
arr = [{"name":"rahul","age":23}, {"name":"Jack","age":22},{"name":"James","age":23}]
From the above array obj I want to get the count of people whose age is 23. In this case the expectation is 2.
I tried:
myArray.filter(x => x == searchValue).length;
But didn't get the exact answer as my declaration of array is different.
Please do let me know anyother way that I can use for this.
Upvotes: 1
Views: 45
Reputation: 11001
Use destructuring in filter method.
const arr = [
{ name: "rahul", age: 23 },
{ name: "Jack", age: 22 },
{ name: "James", age: 23 }
];
const count = arr.filter(({ age }) => age === 23).length;
console.log(count);
Upvotes: 0
Reputation: 22320
something like that ?
const arr =
[ { "name": "rahul", "age": 23 }
, { "name": "Jack", "age": 22 }
, { "name": "James", "age": 23 }
]
const countAge=x=>arr.reduce((a,c)=>a+=c.age==x?1:0,0)
console.log(countAge(23) )
Upvotes: 0
Reputation: 559
Try like below:
arr.filter(item => item.age == searchValue).length
Each item return object with {name:string, age:number}
type.
Then you should get age
property of the item object and compare it with searchValue
.
arr = [
{"name":"rahul","age":23},
{"name":"Jack","age":22},
{"name":"James","age":23}
]
let searchValue = 23;
console.log(arr.filter(x => x.age == searchValue).length)
Upvotes: 1
Reputation: 3384
Try this
let persons = arr.filter(person => person.age===23)
console.log(persons.length);
Upvotes: 1
Reputation: 607
You should use .age
to get the attribute value and filter on it:
arr = [
{"name":"rahul","age":23},
{"name":"Jack","age":22},
{"name":"James","age":23}];
const count = arr.filter(x => x.age == 23).length;
console.log(count)
Upvotes: 2