1

If I have an array like this:

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

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

Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427

4 Answers4

6

You could map your object and only return the target field, and then use the built in indexOf to get the position:

array1.map(item => item.phraseId).indexOf('def')
Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • 1
    Not downvoting, but this results in 2 iterations of the array as well as the allocation of more memory for the 2nd mapped array, which is unnecessary. – Ryan Wheale Aug 01 '16 at 18:53
5

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.


With ES6 arrow function

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

var pos = array1.findIndex(v => v.phraseId == 'def') + 1;

console.log("Position of the object " + pos);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • 2
    I did not know that `findIndex` was an official ECMAScript 6 thing. Neat. – StriplingWarrior Aug 01 '16 at 18:40
  • 1
    I think this solution better than `.map()` because `findIndex()` it's native JS method returns an index in the array unlike `.map` wich used for array iteration. Interesting to see some benchmarks of this two methods. – semanser Aug 01 '16 at 18:44
  • Since we're using the latest cool stuff, why not write it the easy way: `var pos = array1.findIndex(v => v.phraseId === 'def');` – Ryan Wheale Aug 01 '16 at 18:51
1

It works this way :

array1.forEach((elem, index) => {if (elem.phraseId === "def")
   console.log("index = " + index);
});
kevin ternet
  • 4,514
  • 2
  • 19
  • 27
1

Assuming that your key is know (that you know you are looking for a phraseId always) then you can simply iterate through the array with a normal for loop if you are using "traditional" JS, or with a forEach if you are using ES6. Here's the simple for implementation.

for (var i = 0; i < array1.length; i++ ){
    if(array[i].phraseId === 'def') {
    // we know "i" is the index, so do something...
    }
}

To make it more generic so you can search any array for any key, make a function of it that returns the index:

function whatIndex (arr, key, val) {
    for (var i = 0; i < arr.length; i++) {
        if( arr[i][key] === val ) {
            return i;
        }
    }
}
veddermatic
  • 1,082
  • 7
  • 15