Ziv Ofir
Ziv Ofir

Reputation: 103

Finding the number of unique objects in an array in Angular 7

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.

Upvotes: 2

Views: 1081

Answers (2)

Jelle
Jelle

Reputation: 2176

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

Upvotes: 3

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41387

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)

Upvotes: 1

Related Questions