Is javascript's IndexOf method more efficient than iterating through an array?

I have an array of JSON objects and I want to find an object with a specific property. I know this may look like a duplicate question, but please continue, because I think this is a little different from the previous questions.

The guy I work with suggested using IndexOf, and that made me think. Is there something similar to the $ elemMatch function in mangoes? Is there any command that basically says, in the pseudocode, "get me an object with this property from this array"? With iteration, I feel that psuedo-code says: “Look at the first object in this array. If this object has this property, get me this object. If not, look at the second object in this array .....”

I understand how to use IndexOf, as my friend suggested, but the more I thought about it, I began to think that there could be fewer lines of code in the IndexOf method, but in the end it did not need to go through the objects into an array to find the index the one I need? Therefore, if I want to do something with an object with this property, and I use the IndexOf method to get the index, then I would go to an object like myArray [indexFromIndexOfMethod] and then change it accordingly, right? So, if javascript iterates through the array itself to execute the IndexOf method, why don't I just write my own iteration and save the step? Now, if the IndexOf method uses a more efficient way of finding an array element than just repeating and checking each one,then it will be useful for me to use it. Otherwise, it makes no sense to use the IndexOf method if you can achieve the same results with a simple iteration.

+4
2

Array.prototype.indexOf . , . , for, indexOf -, for, .

, . .foo, :

var byFoo = {}
for (var i = 0; i < myArray.length; i++) {
    byFoo[myArray[i].foo] = myArray[i];
}

byFoo['baz'].

, , , . .

+2

indexOf , , , , indexOf.

, JSON - , .

, , , , , , , , .

// This will fail:
var data = [
    {
        'id' : 1,
        'value' : 'myDataForObj1'
    },
    {
        'id' : 2,
        'value' : 'myDataForObj2'
    }
];

data.indexOf({
    'id' : 2,
    'value' : 'myDataForObj2'   
}); // return -1, as in, not found.


// This will work:
var data = [
    '{"id":1,"value":"myDataForObj1"}',
    '{"id":2,"value":"myDataForObj2"}'
];

data.indexOf('{"id":2,"value":"myDataForObj2"}'); // return 1, as in the second element in the array.

// This is what I usually use:
var data = {
    'id1' :     {
        'id' : 1,
        'value' : 'myDataForObj1'
    },
    'id2' : {
        'id' : 2,
        'value' : 'myDataForObj2'
    }
};

data['id2'].value = 'newValue';

- , , , , - , , , .

, "", , . , . , data, , , , , . .

+1

Source: https://habr.com/ru/post/1620557/


All Articles