Skip to content
Advertisement

indexOf() when array-elements are objects (javascript)

For instance, a variable named arrayElements of type array contains:
[{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 id === 3(3rd element) in the arrayElements variable besides using loop?

thanks.

Advertisement

Answer

You have to loop at one point. But you can abstract it to look like you’re not looping

function indexOfCallback(arr, callback, startIndex) {
    if (typeof startIndex == 'undefined') {
        startIndex = 0;
    }
    for(var i=startIndex; i < arr.length; i ++) {
        if (callback(arr[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 on value === 6
console.log(indexOfCallback(array, function(obj){
    return obj.value === 6;
}));

As mentioned by Anthony, this is proposed for ECMAScript 6. Here’s the more complete polyfill https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

if (!Array.prototype.findIndex) {
  Array.prototype.findIndex = function(predicate) {
    if (this == null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return i;
      }
    }
    return -1;
  };
}
console.log(array.findIndex(function(obj){
    return obj.id === 3;
}));
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement