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;
Use filter
and length
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With