0

Say I have an array of objects called friends

let friends = [
    {"name": "test 1", "type": "pending"}, 
    {"name": "test 2", "type": "friends"}, 
    {"name": "test 3", "type": "friends"},
    {"name": "test 4", "type": "friends"},
    {"name": "test 5", "type": "alien"}
]

how would I get the length of friends where pending would be excluded? I'm using this, but is there an easier way?

let total = friends.filter(friend=>friend.type==='friends').length + friends.filter(friend=>friend.type==='alien').length;
totalnoob
  • 2,521
  • 8
  • 35
  • 69

2 Answers2

2

You don't need to filter that array to create a new array and then get its length, just use the function reduce to make a simple count.

let friends = [    {"name": "test 1", "type": "pending"},     {"name": "test 2", "type": "friends"},     {"name": "test 3", "type": "friends"},    {"name": "test 4", "type": "friends"},    {"name": "test 5", "type": "alien"}],
    count = friends.reduce((a, t) => a + (t.type !== 'pending'), 0);

console.log(count);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Ele
  • 33,468
  • 7
  • 37
  • 75
1

You can directly do with single filter query with !=

DEMO

let friends = [
    {"name": "test 1", "type": "pending"}, 
    {"name": "test 2", "type": "friends"}, 
    {"name": "test 3", "type": "friends"},
    {"name": "test 4", "type": "friends"},
    {"name": "test 5", "type": "alien"}
];

let count = friends.filter(t=>t.type !== 'pending').length;

console.log(count);
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396