Функция Underscore.js _.findIndex()
Опубликовано: 7 Октября, 2022
Функция _.findIndex():
- Он используется для поиска индекса элемента, который передается во втором параметре.
- Мы можем использовать это для любого типа массива, такого как массив чисел, массив строк, массив символов и т. д.
- Если мы не знаем, какие все элементы присутствуют в массиве, но хотим узнать, присутствует ли один элемент или нет, то мы используем эту функцию.
Синтаксис:
_.findIndex(array, predicate, [context])
Параметры:
Он принимает три аргумента:
- Массив
- Предикат
- Контекст (необязательно)
Возвращаемое значение:
Он возвращает индекс, в котором присутствует искомый элемент.
Примеры:
- Passing a list of only one key and it’s value to _.findIndex() function:
The ._findIndex() function takes the element from the list one by one and compares it with the element passed as the second parameter. If they match then it returns it’s index otherwise it just skips this element and goes on to the next. This process goes on till the match is not found or the list finishes. If the list finishes without finding the element passed then the result is -1.<!-- Write HTML code here --><html><head><scriptsrc=</script></head><body><scripttype="text/javascript">console.log(_.findIndex([{rollNo:1}, {rollNo:2},{rollNo:3}], { rollNo : 1}));</script></body></html>Output:

- Passing a full structure to the _.findIndex() function:
We can even pass a structure with many properties to the _.findIndex() function and it will work in the same way. For this we also need to mention which property need to be compared. Like in the below example, the array has 3 properties, the is, name, last. Out of these we have mentioned that we want to compare and find out the index of the element with first name as ‘Teddy’.<!-- Write HTML code here --><html><head><scriptsrc=</script></head><body><scripttype="text/javascript">var users = [{"id": 1, "name": "Bobby", "last": "Stark"},{"id": 2, "name": "Teddy", "last": "Lime"},{"id": 3, "name": "Franky", "last": "Frail"},{"id": 4, "name": "Teddy", "last": "Frail"}];console.log(_.findIndex(users, { name: "Teddy"}));</script></body></html>Output:

- Comparing the property with number:
In this we have passed the same structure as the above but we have used the property to match and compare as ‘id’ which contains the numbers. It will work in the same way and compare all the ids until we get id as ‘3’ which is mentioned in the second parameter.<!-- Write HTML code here --><html><head><scriptsrc=</script></head><body><scripttype="text/javascript">var users = [{"id": 1, "name": "Bobby", "last": "Stark"},{"id": 2, "name": "Teddy", "last": "Lime"},{"id": 3, "name": "Franky", "last": "Frail"},{"id": 4, "name": "Teddy", "last": "Frail"},{"id": 3, "name": "Tinu", "last": "Thauus"}];console.log(_.findIndex(users, { id : 3}));</script></body></html>Output:

- Passing an element in the second parameter which is not present in the list:
If we pass an element which the list does not contain then the result will be a negative number -1. There will be no errors. This is the case where the list ends but the element is not present in it.<!-- Write HTML code here --><html><head><scriptsrc=</script></head><body><scripttype="text/javascript">var users = [{"id": 1, "name": "Bobby", "last": "Stark"},{"id": 2, "name": "Teddy", "last": "Lime"},{"id": 3, "name": "Franky", "last": "Frail"},{"id": 4, "name": "Teddy", "last": "Frail"},{"id": 3, "name": "Tinu", "last": "Thauus"}];console.log(_.findIndex(users, { id : 100}));</script></body></html>Output:

ПРИМЕЧАНИЕ:
Эти команды не будут работать в консоли Google или в Firefox, так как необходимо добавить эти дополнительные файлы, которых они не добавили.
Итак, добавьте указанные ссылки в свой HTML-файл, а затем запустите их.
Ссылки следующие:
Пример показан ниже: