Reputation: 3695
I need to perhaps write a function that just outputs the index of an object inside an array, obviously, using $.inArray returns this just fine in the example below.
array = ['one', 'two', 'three'];
$.inArray('one', array) // 0
With a more elaborate array, How can I find the index of the objects nested within?
array = [
{
name: 'One', // index??
data: {
title: 'Title One',
content: 'Content One'
}
},
{
name: 'Two',
data: {
title: 'Title Two',
content: 'Content Two'
}
},
{
name: 'Three',
data: {
title: 'Title Three',
content: 'Content Three'
}
}
];
I've heard of the $.grep() method, indexOf() .. not sure which one to use to just return an integer of the index the object is in
Upvotes: 3
Views: 4456
Reputation: 51461
No built in functions.. but it's easy to write all flavours of your own. And as an exercise you can also use them to extend jQuery,
var array = [{
name: 'One',
// index??
data: {
title: 'Title One',
content: 'Content One'
}},
{
name: 'Two',
data: {
title: 'Title Two',
content: 'Content Two'
}},
{
name: 'Three',
data: {
title: 'Title Three',
content: 'Content Three'
}}];
function findByName(name) {
var index;
$(array).each(function(i, e) {
if (e.name && e.name == name) {
index = i;
return false;
}
});
return index;
}
console.log(findByName("One")); // prints 0
// and now even better ... find by any property
function findByProperty(objects, prop, value) {
var index;
$(objects).each(function(i, e) {
if (e[prop] && e[prop] == value) {
index = i;
return false;
}
});
return index;
}
// usage
var index = findByProperty(array, "name", "One");
console.log(index); // prints 0
index = findByProperty(array, "name", "Three");
console.log(index); // prints 2
// and even more powerful
function findByFilter(objects, filter) {
var index;
$(objects).each(function(i, e) {
if (filter(i, e)) {
index = i;
return false;
}
});
return index;
}
index = findByFilter(array,function(i,e){ return e.data.title=="Title Two"; });
console.log(index); // prints 1
Upvotes: 2
Reputation: 11352
You can use the name
property as index.
Try this code:
var indexOfObj = function(array,objName){
var len = array.length;
while(--len>=0 && array[len].name!==objName);
return len;
}
This function will return -1
if the obj wasn't found in the array.
Upvotes: 0
Reputation: 32608
You don't need a pre-written function, just iterate over your array and compare the name
property:
function findValue(array, nameWeAreLookingFor) {
for(var i = 0; i<array.length; i++) {
if(array[i].name === nameWeAreLookingFor) return i;
}
return -1;
}
Upvotes: 5