Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Revisions

2 of 3
insert duplicate link

Trouble using indexOf on a complex array

Possible Duplicate:
indexOf method in an object array?

I have a javascript array which follows this format:

var arrayName = [
{id: "a", gender: "man", item: "stuff"},
{id: "b", gender: "woman", item: "stuff"},
{id: "c", gender: "man", item: "stuff"},
{id: "d", gender: "man", item: "stuff"}
];

Is there a way that I can use array.indexOf to find an index in the array, when for example I know the "id" variable.

For example I tried;

var position = arrayName.indexOf("b");
arrayName[position].gender = "man"

At the moment I am using;

for(var i=0; i<arrayName.length; i++) {
 if(arrayName[i].id == "b"){
 arrayName[i].gender = "man";
 }
}

This second technique works but the actual array I am using has 150 entries and 10 items in each entry so looping through it all seems very wasteful when I know the "id" of the entry I want to edit. indexOf would be a much cleaner approach if I can get it working.

Nick
  • 345
  • 2
  • 3
  • 7
lang-js

AltStyle によって変換されたページ (->オリジナル) /