2

Say I have a following array which contains the following objects:

array = [{name: 'foo', number: 1}, {name: 'foo', number: 1}, {name: 'bar', number: 1}]

How would I go about finding the number of foo in this array? I am currently doing

search(name, array) {
    let count = 0;
    for (let i = 0; i < array.length; i++) {
      if (array[i].name=== name) {
        count++;
      }
    }
    return count;
  }

I would like to be able to run the search() function and be able to get the number of objects which has name foo and the number of objects which has name bar instead of having to pass in the name of the object itself.

2 Answers 2

3

let array = [{
  name: 'foo',
  number: 1
}, {
  name: 'foo',
  number: 2
}, {
  name: 'bar',
  number: 1
}]

function count(input) {
  var output = {};

  array.forEach(item => {
    if (output[item.name]) {
      output[item.name] += item.number;
    } else {
      output[item.name] = item.number;
    }
  });

  return output;
}

var result = count(array);
console.log(result);

You can iterate over the items and add the counts for each name that is the same. Hope this is what you were looking for, otherwise let me know

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

1 Comment

Yes, this was exactly what I was looking for! Thanks!
1

Use the filter function

let array = [{name: 'foo', number: 1}, {name: 'foo', number: 1}, {name: 'bar', number: 1}]

let count = array.filter(e => e.name === "foo").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.