- Array.prototype.indexOf()
- Try it
- Syntax
- Parameters
- Return value
- Description
- Examples
- Using indexOf()
- Finding all the occurrences of an element
- Finding if an element exists in the array or not and updating the array
- Using indexOf() on sparse arrays
- Calling indexOf() on non-array objects
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- Как узнать индекс элемента в массиве js
Array.prototype.indexOf()
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Try it
Syntax
indexOf(searchElement) indexOf(searchElement, fromIndex)
Parameters
Element to locate in the array.
Zero-based index at which to start searching, converted to an integer.
Return value
The first index of the element in the array; -1 if not found.
Description
The indexOf() method compares searchElement to elements of the array using strict equality (the same algorithm used by the === operator). NaN values are never compared as equal, so indexOf() always returns -1 when searchElement is NaN .
The indexOf() method skips empty slots in sparse arrays.
The indexOf() method is generic. It only expects the this value to have a length property and integer-keyed properties.
Examples
Using indexOf()
The following example uses indexOf() to locate values in an array.
const array = [2, 9, 9]; array.indexOf(2); // 0 array.indexOf(7); // -1 array.indexOf(9, 2); // 2 array.indexOf(2, -1); // -1 array.indexOf(2, -3); // 0
You cannot use indexOf() to search for NaN .
const array = [NaN]; array.indexOf(NaN); // -1
Finding all the occurrences of an element
const indices = []; const array = ["a", "b", "a", "c", "a", "d"]; const element = "a"; let idx = array.indexOf(element); while (idx !== -1) indices.push(idx); idx = array.indexOf(element, idx + 1); > console.log(indices); // [0, 2, 4]
Finding if an element exists in the array or not and updating the array
function updateVegetablesCollection(veggies, veggie) if (veggies.indexOf(veggie) === -1) veggies.push(veggie); console.log(`New veggies collection is: $veggies>`); > else console.log(`$veggie> already exists in the veggies collection.`); > > const veggies = ["potato", "tomato", "chillies", "green-pepper"]; updateVegetablesCollection(veggies, "spinach"); // New veggies collection is: potato,tomato,chillies,green-pepper,spinach updateVegetablesCollection(veggies, "spinach"); // spinach already exists in the veggies collection.
Using indexOf() on sparse arrays
You cannot use indexOf() to search for empty slots in sparse arrays.
.log([1, , 3].indexOf(undefined)); // -1
Calling indexOf() on non-array objects
The indexOf() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length .
const arrayLike = length: 3, 0: 2, 1: 3, 2: 4, 3: 5, // ignored by indexOf() since length is 3 >; console.log(Array.prototype.indexOf.call(arrayLike, 2)); // 0 console.log(Array.prototype.indexOf.call(arrayLike, 5)); // -1
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jun 27, 2023 by MDN contributors.
Your blueprint for a better internet.
Как узнать индекс элемента в массиве js
Чтобы узнать индекс элемента в массиве в JS, можно воспользоваться методом indexOf() . Этот метод вернёт первый индекс, по которому указанный элемент находится в массиве:
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']; console.log(beasts.indexOf('bison')); // => 1
Если такого элемента в массиве нет, то метод вернет -1
console.log(beasts.indexOf('giraffe')); // => -1
Помимо стандартных возможностей JS, узнать индекс элемента массива можно с помощью метода из библиотеки Lodash _.findIndex():
Метод возвращает индекс первого элемента в массиве, который удовлетворяет условию. Если ни один из элементов не удовлетворяет условию поиска, возвращается -1. Этот метод отлично ладит с массивами, элементами которых являются объекты. Обратимся к примеру ниже:
const users = [ 'user': 'kris', 'active': false >, 'user': 'john', 'active': false >, 'user': 'luk', 'active': true > ]; const findUserItem = _.findIndex(users, 'user': 'john', 'active': false >); console.log(findUserItem); // => 1 - индекс искомого элемента
В примере выше всё понятно, давайте посмотрим возможности этого метода в следующем примере.
const findUserItem = _.findIndex(users, ['active', false]); console.log(findUserItem); // => 0
В примере выше нам не важно имя пользователя, нам просто нужно найти пользователя, у которого был бы неактивный статус. И данный метод нам в этом отлично поможет.