2

I know given a single key (for example, if I know the object.name = 'Sam') using:

var index = array.map(function(el) {return el.name}).indexOf('Sam');

I can get the index of the array element with object.name = 'Sam' However say I have several elements with object.name ='Sam' in the array, but now I know know the object.name, object.age and object.size - is it possible to adapt the above code to get the index but also checking against object.age and object.size?

AlwaysNeedingHelp
  • 1,851
  • 3
  • 21
  • 29

3 Answers3

0

Assuming you have the values in variables such as name, age and size as you mentioned in comments, You can use a function like:

function findInArray(arr) {
  for (var i = 0; i < arr.length; i++) {
    var el = arr[i];
    if (el.name == name && el.age == age && el.size == size)
        return i;
  }
 return -1;
};

Which will return the index of object in array if match is found, and -1 otherwise...

var data = [{
    name: "Sis",
    age: "17",
    size: "10"
  }, {
    name: "Sam",
    age: "17",
    size: "10"
  }, {
    name: "Som",
    age: "17",
    size: "10"
  }],
  name = "Sam",
  age = "17",
  size = "10";

function findInArray(arr) {
  for (var i = 0; i < arr.length; i++) {
    var el = arr[i];
    if (el.name == name && el.age == age && el.size == size)
      return i;
  }
  return -1;
};
console.log(findInArray(data));
T J
  • 42,762
  • 13
  • 83
  • 138
0

If you're using the awesome underscore library there's a _.findWhere function.

var sam21 = _.findWhere(people, {
  name: 'Sam', 
  age: 21
}); 

if you want something without a whole other library you can use .filter.

var sam21 = people.filter(function(person) {
  return person.age === 21 && person.name === 'Sam';
});

I just noticed you're looking for the index. This answer can be useful: https://stackoverflow.com/a/12356923/191226

Community
  • 1
  • 1
Bill Criswell
  • 32,161
  • 7
  • 75
  • 66
0

You could use a function like this one

indexOfObjectArray = function(array, keyvalues) {
for (var i = 0; i < array.length; i++) {
    var trueCount = 0;
    for (var j = 0; j < keyvalues.length; j++) {
        if (array[i][keyvalues[j]['key']] == keyvalues[j]['value']) {
            trueCount++;
        }
    }
    if (trueCount === keyvalues.length) return i;
}
return -1; }

and use it like that for example:

var yourArray = [{id: 10, group: 20},...];
var keyvalues = [
{ 'key': 'id', 'value': 10 },
{ 'key': 'group', 'value': 20 }]; 

var index = indexOfObjectArray(yourArray, keyvalues );

This function will return the index of an object that has id = 10 and group = 20

Xaris Fytrakis
  • 487
  • 6
  • 16