1

I have an below array. I wanted to know how many time selectedOption key is present in array of Object. In, some object we don't have key selectedOption. So, the count of key selectedOption should return 4. How we can count these key in javascript ?

let data = [{
  id: 123,
  selectedOption: "ABC",
  value: 345
}, {
  id: 234,
  selectedOption: "BCD",
  value: 345
}, {
  id: 356,
  selectedOption: "BGY",
  value: 678
}, {
  id: 456,
  selectedOption: "BCD",
  value: 890
}, {
  id: 870: value: 980
}, {
  id: 385,
  value: 654
}]
1
  • 2
    What have you tried so far to solve this on your own? A simple loop with an if (typeof ...) should do the job. Commented Jun 13, 2020 at 12:02

3 Answers 3

6
data.filter(datum => datum.selectedOption).length
Sign up to request clarification or add additional context in comments.

Comments

1

data.filter(d => d.hasOwnProperty('selectedOption')).length

This is a more full proof solution compared to data.filter(datum => datum.selectedOption).length because if selectedOption was a boolean flag with false value it wouldn't be counted.

hasOwnProperty will check if the property exists on the object irrespective of the value.

For example in this case

let data = [{
  id: 123,
  selectedOption: false,
  value: 345
}, {
  id: 234,
  selectedOption: false,
  value: 345
}, {
  id: 356,
  selectedOption: true,
  value: 678
}, {
  id: 456,
  selectedOption: false,
  value: 890
}, {
  id: 870,
  value: 980
}, {
  id: 385,
  value: 654
}];
  1. data.filter(d => d.hasOwnProperty('selectedOption')).length Output: 4

  2. data.filter(datum => datum.selectedOption).length Output: 1

2 Comments

While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
@β.εηοιτ.βε thanks for the suggestion, I've added an explanation.
0

There are multiple ways it can be done. In the below function ,reduce is used. Inside reduce callback it is checking if the object has selectedOption key then increment 1

let data = [{
  id: 123,
  selectedOption: "ABC",
  value: 345
}, {
  id: 234,
  selectedOption: "BCD",
  value: 345
}, {
  id: 356,
  selectedOption: "BGY",
  value: 678
}, {
  id: 456,
  selectedOption: "BCD",
  value: 890
}, {
  id: 870,
  value: 980
}, {
  id: 385,
  value: 654
}];

let countSelectedOption = data.reduce((acc, curr) => {
  acc += curr.selectedOption ? 1 : 0;
  return acc;
}, 0);
console.log(countSelectedOption)

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.