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?

2

4 Answers 4

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')
Sign up to request clarification or add additional context in comments.

1 Comment

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

3 Comments

I did not know that findIndex was an official ECMAScript 6 thing. Neat.
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.
Since we're using the latest cool stuff, why not write it the easy way: var pos = array1.findIndex(v => v.phraseId === 'def');
1

It works this way :

array1.forEach((elem, index) => {if (elem.phraseId === "def")
   console.log("index = " + index);
});

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.