Samantha J Samantha J - 2 months ago 5x
Javascript Question

How can I find out the array position of an object by searching the array?

If I have an array like this:

var array1 =

How can I find out that the object with phraseId of "def" has the 2nd position?


Use native JavaScript findIndex method.

var array1 = [{
  "phraseId": "abc",
  "keyword": "bb",
  "posId": 1
}, {
  "phraseId": "def",
  "keyword": "bb",
  "posId": 1
}, ];

var pos = array1.findIndex(function(v) {
  // set your condition for finding object             
  return v.phraseId == 'def';
  // add `1` since you want to count from `1`            
}) + 1;

console.log("Position of the object " + pos);

For older browser check polyfill option.