Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand method to count length of array

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;
like image 937
sam Avatar asked Nov 16 '17 08:11

sam


2 Answers

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)
like image 194
Sajeetharan Avatar answered Nov 15 '22 12:11

Sajeetharan


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.

like image 26
Naman Kheterpal Avatar answered Nov 15 '22 12:11

Naman Kheterpal