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

11 years ago, September 26, 2013
Reading time: 1 mins

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
Create filled circle to visualize data using svg
Next
General error: 2006 MySQL server has gone away
© 2024 Anil Maharjan