0

I am having a data with multiple options, of which only one will be having the value correct to be true. I need to find the index of this particular data. I have achieved it with the below code. But however I want to know if there are any performance implication for this method and if there is any better method when I am using Angular Js.

 var data = [      

                  {"option": "8",      "correct": false},
                  {"option": "14",     "correct": false},
                  {"option": "10",      "correct": true},
                  {"option": "23",     "correct": false} 

 ];

var i = data.length;
while(i--) {
    if (data[i].correct == true){
        alert("Option:"+ data[i].option + " Index:"+ i);
    break;    

    }       
} 
esafwan
  • 17,311
  • 33
  • 107
  • 166
  • 1
    There is no other way to find an object with a particular property value in an array of objects besides a brute force search like this unless you prepare the data ahead of time some other way. Your particular search is searching backwards through the array which will obviously yield a different value than searching forwards (if there are multiple matches). – jfriend00 Oct 25 '14 at 09:26
  • 1
    It is basically the only way of doing this. However, As a side remark, be aware that this will fail if value isn't found. [this answer](http://stackoverflow.com/questions/8668174/indexof-method-in-an-object-array) is what your looking for instead. Regarding performance, it could only become a problem if the array is very big... – Laurent S. Oct 25 '14 at 09:27

1 Answers1

1

No there is no other way to find a value in array, unless you loop through it completely, which would be O(n).

You can however, improve the search if your array is sorted on the basis of the field which you are using for search. You can use binary search in that case, which would be O(log n).

The search would have performance implications, if the array is too big. Also it has nothing to do with angular.

esafwan
  • 17,311
  • 33
  • 107
  • 166
harishr
  • 17,807
  • 9
  • 78
  • 125