How to use the indexOf function from underscore

Find comprehensive JavaScript underscore.indexOf code examples handpicked from public code repositorys.

_.indexOf is a function in Underscore.js library that returns the index at which the first occurrence of a given element can be found in an array.

2318
2319
2320
2321
2322
2323
2324
2325
2326
// passed-in arrays.
_.intersection = function(array) {
  var rest = slice.call(arguments, 1);
  return _.filter(_.uniq(array), function(item) {
    return _.every(rest, function(other) {
      return _.indexOf(other, item) >= 0;
    });
  });
};
fork icon0
star icon2
watch icon0

13
14
15
16
17
18
19
20
21
22
    var _index;
    _index = ids.indexOf(doc[id_key]);
    if (_index > -1) {
      return _index;
    } else {
      return ids.length + _.indexOf(values, doc[id_key]);
    }
  });
} else {
  return _.sortBy(docs, function(doc) {
fork icon0
star icon0
watch icon1

How does underscore.indexOf work?

underscore.indexOf function in JavaScript is used to find the index of a given value in an array by iterating through the elements of the array and returning the index of the first match it finds. It uses strict equality comparison to check if the value is present in the array. If the value is not found in the array, it returns -1.

Ai Example

1
2
3
const arr = [2, 4, 6, 8, 10];
const index = _.indexOf(arr, 6);
console.log(index); // Output: 2

In this example, we have an array of numbers arr. We then use _.indexOf() to find the index of the number 6 within the array. The function returns the index 2 where 6 is located in the array.