-2

How do I calculate the unique values of an object property when I have an array of objects?

let organisations = [
  {
    "id": 1,
    "name": "nameOne",
  },
  {
    "id": 2,
    "name": "nameTwo",
  },
  {
    "id": 3,
    "name": "nameOne",
  }
]

In this case, how do I calculate the number of unique organisation names. The answer here is two, because there are two unique names.

This doesn't work

 var counts = this.filteredExtendedDeals.reduce(
        (organisations, name) => {
          counts[name] = (counts[name] || 0) + 1;
          return counts;
        },
        {}
      );
      return Object.keys(counts);
F_SO_K
  • 13,640
  • 5
  • 54
  • 83
  • reduce or filter – mplungjan Sep 15 '20 at 15:20
  • @mplungjan You didn't specify an issue with the question but if its the lack of an attempt, that is now included – F_SO_K Sep 15 '20 at 15:23
  • The attempt does not make any sense. You are not running on the same object you show and you are returning outside a function. Please make a [mcve] using the snippet editor. – mplungjan Sep 15 '20 at 15:25
  • 1
    You can use map with a Set: `new Set(organisations.map(({name}) => name)).size;` – Nick Parsons Sep 15 '20 at 15:27
  • Reduce, no set needed: `const names = organisations.reduce((acc,org) => { if (acc.includes(org.name)) return acc; acc.push(org.name); return acc},[])` – mplungjan Sep 15 '20 at 15:33

1 Answers1

5

You could reduce the list into a Set and then grab the size.

const organisations = [
  { "id": 1, "name": "nameOne" },
  { "id": 2, "name": "nameTwo" },
  { "id": 3, "name": "nameOne" }
];

const uniqueItems = (list, keyFn) => list.reduce((resultSet, item) =>
    resultSet.add(typeof keyFn === 'string' ? item[keyFn] : keyFn(item)),
  new Set).size;

console.log(uniqueItems(organisations, 'name'));
console.log(uniqueItems(organisations, ({ name }) => name));
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • Why set? `const names = organisations.reduce((acc,org) => { if (acc.includes(org.name)) return acc; acc.push(org.name); return acc},[])` – mplungjan Sep 15 '20 at 15:33
  • 2
    @mplungjan A `Set` is more efficient than checking `Array` item indices. The lookup is O(1). – Mr. Polywhirl Sep 15 '20 at 15:36
  • Interesting read https://stackoverflow.com/questions/39007637/javascript-set-vs-array-performance – mplungjan Sep 16 '20 at 05:24