0
var arr = [{code:'A', number: 1}, {code:'A', number: 2}, {code:'B', number: 3 }]

How can I get a number of objects that has certain key in above array?

For example, The number of code: 'A' objects is 2.

How to get it?

2 Answers 2

1

filter will iterate through the array and execute your callback function. The callback function needs to evaluate to a boolean for the value to return.

var arr = [{code:'A', number: 1}, {code:'A', number: 2}, {code:'B', number: 3 }]
arr.filter(function(x) { return x.code === 'A'}).length
Sign up to request clarification or add additional context in comments.

Comments

1

Iterate through the array and store the informations like count and corresponding numbers in an object structure.

var arr = [{code:'A', number: 1}, {code:'A', number: 2}, {code:'B', number: 3 }];

var obj = {};
debugger;
for (var i =0, len = arr.length; i < len; i += 1) {
  ele = arr[i];
  code = ele.code
  if (!obj[code]) {
    obj[code] = {
      count: 0,
      number: []
    };
  }
  obj[code].count += 1;
  obj[code].number.push(ele.number);
}

function getCount(code) {
  return obj[code].count;
}

console.log(getCount('A')); // 2
console.log(getCount('B')); // 1
console.log(obj);

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.