-2

I have an array of objects that looks similar to this one:

const myArray = [
    {
        message: "foo",
        seen: false
    },
    {
        message: "bar",
        seen: false
    },
    {
        message: "foobar"
        seen: true
    }
];

I would like to count the number of object in my array where the seen property is set to false.

I know how to do it with a classic For loop but I wanted to know if there was a more efficient way to do so ?

Thank you, any help much appreciated.

EDIT: Here are my codes with for loops

var count = 0;
    for (var x in myArray) {
        if(!x.seen) {
            count++;
        }
    }

and

    var count = 0;
    myArray.forEach(e => {
        if(!e.seen) {
            count++;
        }
    })
nsayer
  • 799
  • 2
  • 8
  • 21

2 Answers2

2

You could use filter.

const myArray = [
  {
    message: "foo",
    seen: false,
  },
  {
    message: "bar",
    seen: false,
  },
  {
    message: "foobar",
    seen: true,
  },
];

const result = myArray.filter(x => !x.seen).length;

console.log(result);
wisn
  • 974
  • 10
  • 17
0

The answer is here. https://stackoverflow.com/a/49105977/6192621

The fastest way is the reverse simple loop.

for(i = myArray.length - 1; i > 0; i--) if(!myArray[i].seen) count++;
Joseba
  • 98
  • 2
  • 3