Skip to content

Instantly share code, notes, and snippets.

@tombowers
Last active August 29, 2015 14:08
Show Gist options
  • Save tombowers/08ceabcbf4a3154d5674 to your computer and use it in GitHub Desktop.
Save tombowers/08ceabcbf4a3154d5674 to your computer and use it in GitHub Desktop.
How to search for an object in a Javascript array, and fast!
var food = {
fruit: [
{ name: 'banana', value: 'joke fruit', type: 'fruit' },
{ name: 'apple', value: 'newtonian legend', type: 'fruit' }
],
vegetables: [
{ name: 'cabbage', value: 'filth', type: 'vegetable' },
{ name: 'broccoli', value: 'green evil', type: 'vegetable' }
]
};
var food = [
{ name: 'banana', value: 'joke fruit', type: 'fruit' },
{ name: 'apple', value: 'newtonian legend', type: 'fruit' },
{ name: 'cabbage', value: 'filth', type: 'vegetable' },
{ name: 'broccoli', value: 'green evil', type: 'vegetable' }
];
function getFood(name, context) {
var obj, i, il;
for (i = 0, il = food[context].length; i < il; i++) {
if (food[context][i].name == name) {
obj = food[context][i];
break;
}
}
return obj;
}
function getFood(name, context) {
var obj, i, il;
if (context) {
for (i = 0, il = food[context].length; i < il; i++) {
if(food[context][i].name == name) {
obj = food[context][i];
break;
}
}
} else {
for (i = 0, il = food.length; i < il; i++) {
for (j = 0, jl = food[i].length; j < jl; j++) {
if(food[i][j].name == name) {
obj = food[i][i];
break;
}
}
if (obj) {
break;
}
}
}
return obj;
}
broccoliObject = getFood('broccoli');
// Or
broccoliObject = getFood('broccoli', 'vegetable');
function getFood(name) {
var obj, i, il;
for (i = 0, il = food.length; i < il; i++) {
if (food[i].name == name) {
obj = food[i];
break;
}
}
return obj;
}
var broccoliObject = food[foodIndex.broccoli];
var food = [
{ key: 21, name: 'banana', value: 'joke fruit', type: 'fruit' },
{ key: 52, name: 'apple', value: 'newtonian legend', type: 'fruit' },
{ key: 2, name: 'cabbage', value: 'filth', type: 'vegetable' },
{ key: 15, name: 'broccoli', value: 'green evil', type: 'vegetable' }
];
var foodIndex = {
banana: 0,
apple: 1,
cabbage: 2,
broccoli: 3
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment