Reputation: 698
I have an array like this
var arr = [{a:1, ...},{a:1, ...},{c:2, ...},{a:3, ...},{a:1, ...}]
how can I get the length of array where arr[x].a != 1
.
I know this can be done using for loop
and push
but I want to follow the best practise as every decent programmer should do.
P.S FYI I am using AngularJS.
EDIT 1
For anyone facing issues with arrow function
in sajeetharan's answer because of ES6 script here is the solution
arr.filter(function(a){return a.a != 1}).length;
Upvotes: 15
Views: 3329
Reputation: 13346
You can use array.prototype.filter
and array.length
:
var length = arr.filter(el => el.a !== 1).length
Upvotes: 15
Reputation: 222532
const result = arrayToCount.filter(i => i.a != 1 ).length;
As @Naman Kheterpal
mentioned below, Another way is to use reduce
const result = arrayToCount.reduce((c, o) => o + (o.a === 1), 0)
Upvotes: 21
Reputation: 1840
The most memory efficient way for this is:
const result = arr.reduce((count,el)=> count+ (el.a!==1)},0)
filter
creates a complete new array, reduce
only creates a new var.
And both of them iterates over the array once.
Upvotes: 17