-1

I have an array of objects:

const array1 = [
   {'name': 'name', 'age': 12},
   {'name': 'name1', 'age': 14},
   {'name': 'name2', 'age': 16}
];
   // I want to find index of name1

I want to find index of the object having 'name':'name1'. How do I do this?

2

2 Answers 2

0

Try to use below Code to find the index

Using for loop:

var array1 = [
   {'name': 'name', 'age': 12},
   {'name': 'name1', 'age': 14},
   {'name': 'name2', 'age': 16}
];

var index;
for(i=0;i<array1.length;i++) {
  if (array1[i].name == "name1") { 
  index = i; break;
 } } 
console.log(index);

Using Filter or find method of array If only one matched condition.

const array1 = [
   {'name': 'name', 'age': 12},
   {'name': 'name1', 'age': 14},
   {'name': 'name2', 'age': 16}
];
var x=array1.find(function(a,i) { if(a.name =="name1") {a.index = i; return i;}}).index

var y= array1.filter(function(a,i) { if(a.name =="name1") { a.index = i;return i;}})[0].index;
console.log(x);
console.log(y);

Note: Condition matched at multiple position then find method returns first occurrence and filter method will return all occurrences.

Sign up to request clarification or add additional context in comments.

6 Comments

Why do you want to reinvent the wheel? You have .findIndex. Also .map + .filter is not required. If you want to do thinf=gs manually, try var index = -1; array1.some((x, i) => { if(a.name =="name1") { index = il return true; } })
Yes agreed.. then we can write using basic for loop also
@ rajesh array.some method doesn't work in IE 11.Please find the updated code var index;for (var i = 0; i < array1.length; ++i) { if (array1[i]name == 'name1') { index = i; break; } } console.log(index); before doing downvote check your solution properly.
dear friend, using 2 looping structure is still not acceptable. If you would have used the code in the comment, you would have not received the vote. Also, browser compatibility is something good to look for, but it can be avoided if you used babel loaders or polyfills. Also, it is supported by IE9 onwards reference. Also please mind the tone.
@ Rajesh updated the code Please check.
|
-2

You can use findIndex method like this.

const array1 = [{
    'name': 'name',
    'age': 12
  },
  {
    'name': 'name1',
    'age': 14
  },
  {
    'name': 'name2',
    'age': 16
  }
];
index = array1.findIndex(a => a.name == "name1");

console.log(index);

2 Comments

Missing explanation. What have you changed? Why have you changed? Why does it solve the problem?
I have add array1 defination and explain something like Adding ref to docs Array.prototype.findIndex()