0

Can someone explain this solution to me? A friend helped me, but he just wrote it all out and didn't explain it. Now, I'm really confused :(

_.indexOf = function(array, target){
    var result = -1;
    _.each(array, function(item, index) {
  if (item === target && result === -1) {
    result = index;
  }
});

return result;

};

return result;

};

Rory Perro
  • 441
  • 2
  • 7
  • 16

1 Answers1

0

The function traverses through all the elements of the array and returns index of the first element that is equal to target. The code could also look like this:

_.indexOf = function(array, target){
    var result = -1;
    _.each(array, function(item, index) {
        if (item === target) {
            result = index;
            return false;
        }
    });
    return result;
}
dmitreyg
  • 2,615
  • 1
  • 19
  • 20