2

I have a JS object/ associative array with some values:

var array =[
{val:1,ref:10,rule:100},
{val:1,ref:12,rule:120},
{val:2,ref:13,rule:165},
];

And I want to perform a .length, but want to be able to slice based on one of the keys (for instance val == 1). I want the length of values with val 1 rather than the length of the entire object. I have looked through the references material and could not find a satisfactory answer and I am unsure if this is feasible.

array.val==1.length = 2

Something like that...

  • 1
    [You're looking for the Array `.filter()` method.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) – Pointy Nov 17 '14 at 20:53

2 Answers2

4

You want to .filter the array for elements that match some predicate:

var filteredArray = array.filter(function(element) { return element.val == 1 })
filteredArray.length // = 2

filter applies the callback function to each element in the array, and the new filtered array contains all elements from original array for which the filter callback function returned true. Here, the function returns true for all elements with a val property of 1.

apsillers
  • 112,806
  • 17
  • 235
  • 239
1

You need to use a .filter():

array.filter(function(v){return v.val==1}).length
Scimonster
  • 32,893
  • 9
  • 77
  • 89