Wednesday, 20 September 2017

Searching for objects in JavaScript arrays



How do I search for the property of an object in an array without using for loops in JavaScript?



If the array is a simple one I can use array.indexOf(value) to get the index, but what if the array is an array of objects? Other than looping any other way?




For example, ar = [{x,y},{p,q},{u,v}]. If searched for v, it should return the array index as 2.


Answer



Searching for a value in an array typically requires a sequential search, which requires you to loop over each item until you find a match.



function search(ar, value) {
var i, j;
for (i = 0; i < ar.length; i++) {
for (j in ar[i]) {
if (ar[i][j] === value) return i;
}

}
}

search([{'x': 'y'}, {'p': 'q'}, {'u': 'v'}], 'v'); // returns 2;

No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...