1

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.

5 Answers 5

2

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)

Sign up to request clarification or add additional context in comments.

Comments

1

Try this

let persons = arr.filter(person => person.age===23)
console.log(persons.length);

Comments

1

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)

Comments

0

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) )

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.