indexOf() when array-elements are objects (javascript) -
For example, a variable in the name of the
[html]
< P> {id: 1, value: 5}, {id: 2, value: 6}, {id: 3, value: 7}, {id: 4, value: 8}] . How do I get the position of the array element with the id === 3
addition to using the loop in the arrayElements
variable Do you?
Thank you.
You should have a loop at a point. But you can see that you are not looping
" snippet-code-js lang-js prettyprint-override "> function indexoffrollback (ARI, callback, startendex) {if (type of startIndex == 'undefined') {startIndex = 0; } (Var i = startIndex; i & lt; arr.length; i ++) {if (callback (ARE [i])) {return i; }} Return -1; } Var array = [{id: 1, value: 5}, {id: 2, value: 6}, {id: 3, value: 7}, {id: 4, value: 8}]; Search on // id === 3 console.log (indexOfCallback (array, function (obj) {return obj.id === 3;})); // search at value === 6 console.log (indexOfCallback (array, function (obj) {return obj.value === 6;}));
As Anthony has said, it is proposed for ECMAScript 6. There is more complete polyfill here
if (! Array.prototype.findIndex) {Array.prototype.findIndex = function} {if (this == empty) {new type error ('array . Prototype.Fund is called on blank or undefined '); } If (type of reality! == 'function') {new type error ('predicate should be a function'); } Var list = object (this); Var length = list.length & gt; & Gt; & Gt; 0; Var thisArg = logic [1]; Var values; (Var i = 0; i & lt; length; i ++) for {value = list [i]; If (predicate.call (this ARR, value, I, list)) {return i; }} Return -1; }; } Console.log (array.findIndex (function (obj) {return obj.id === 3;}));