Samantha J Samantha J - 1 year ago 63
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download