user3317592 user3317592 - 2 months ago 5
Javascript Question

Getting index of array object element given multiple object keys

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?

T J T J
Answer

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));

Comments