9/26/2013
Reading time: 1 mins

GET INDEX OF THE ARRAY BY PROPERTY OF ITS ELEMENT OBJECT!

How to get index (offset) of the array of objects when value of a property of its element object is known?

Here is the solution

First create a new array of the elements of the know property only, using the array.map() function. And then chain it with indexOf(knownValue). This will actually give u the index of the value in current new array but is the required index of the element object you are looking for.

var array = [{ name: 'abc', 
  property: 'something',
  anotherproperty: 'somethingelse'
},{},{}];

var index = array.map(function(element) {
  return element.name;
}).indexOf('abc');
Previous
Using gradient stops and transparency to dynamically fill circle partially in svg using d3js
Next
General error: 2006 MySQL server has gone away
© 2024 Anil Maharjan