Atousa Darabi
Atousa Darabi

Reputation: 927

How get the size of a Set object on a specific key value?

I need to know number of items which item.status is true. How can I get it?

const set1 = new Set([
  {
    name: 'AA',
    status: false
  },
  {
    name: 'BB',
    status: true
  },
  {
    name: 'CC',
    status: false
  },
  {
    name: 'DD',
    status: true
  },
  {
    name: 'EE',
    status: false
  }
]);

In this example need to get 2. I want to do something like this:

set1.filter( item => item.status === true ).length

But don't know how filter in Set.

Upvotes: 0

Views: 173

Answers (3)

Kirill Savik
Kirill Savik

Reputation: 1278

Please use this code.

const count = Array.from(set1).filter(val => val.status == true).length;

Upvotes: 2

Terry Lennox
Terry Lennox

Reputation: 30715

You could use Array.filter() and then Array.length of the result to find the item count:

const set1 = new Set([ { name: 'AA', status: false }, { name: 'BB', status: true }, { name: 'CC', status: false }, { name: 'DD', status: true }, { name: 'EE', status: false } ]);

const count = [...set1].filter(item => item.status).length;
console.log("Count:", count)

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075149

There's no shortcut, you have to count them (one way or another):

let count = 0;
for (const {status} of set1) {
    if (status) {
        ++count;
    }
}

const set1 = new Set([
  {
    name: 'AA',
    status: false
  },
  {
    name: 'BB',
    status: true
  },
  {
    name: 'CC',
    status: false
  },
  {
    name: 'DD',
    status: true
  },
  {
    name: 'EE',
    status: false
  }
]);

let count = 0;
for (const {status} of set1) {
    if (status) {
        ++count;
    }
}
console.log(`Count where status is true: ${count}`);

Or if you like reduce for things like this (I don't) you can spread the elements out into an array and the call reduce on it:

const count = [...set1].reduce((acc, {status}) => acc + (status ? 1 : 0), 0);

const set1 = new Set([
  {
    name: 'AA',
    status: false
  },
  {
    name: 'BB',
    status: true
  },
  {
    name: 'CC',
    status: false
  },
  {
    name: 'DD',
    status: true
  },
  {
    name: 'EE',
    status: false
  }
]);

const count = [...set1].reduce((acc, {status}) => acc + (status ? 1 : 0), 0);
console.log(`Count where status is true: ${count}`);

Upvotes: 2

Related Questions