Home>Article>Web Front-end> JavaScript Topic 9: Find the specified element in the array

JavaScript Topic 9: Find the specified element in the array

coldplay.xixi
coldplay.xixi forward
2021-03-12 10:13:33 2896browse

JavaScript Topic 9: Find the specified element in the array

Article Directory

    • 1. findIndex and findLastIndex
        • 1.1 findIndex
        • 1.2 findLastIndex
        • 1.3 Merge findIndex and findLastIndex
    • ## 2. sortIndex
        • 2.1 Traversal
        • 2.2 Dichotomy
    • 3. indexOf and lastIndexOf
      • ##3.1 The first version of indexOf implementation
        • 3.2 The common first version of indexOf and lastIndexOf
        • 3.3 indexOf and lastIndexOf General second edition
      • ##Reference
    • Write at the end
  • (Free learning recommendation:

javascript video tutorial)1. findIndex and findLastIndex

1.1 findIndex

The findIndex() method returns the index of the first element in the array that satisfies the provided test function. If the corresponding element is not found, -1 is returned.

const array1 = [5, 12, 8, 130, 44];const isLargeNumber = (element) => element > 13;console.log(array1.findIndex(isLargeNumber));// expected output: 3

Implementation

Array.prototype.newFindIndex = function(callback) { const _arr = this; const len = _arr.length; for (let i = 0; i element > 13;console.log(array1.newFindIndex(isLargeNumber));// 3
1.2 findLastIndexSimilarly when we look back to find the first method that meets the conditions, we can write like this:

Array.prototype.newFindlastIndex = function(callback) { const _arr = this; const len = _arr.length; for (let i = len - 1; i >= 0; i--) { if (callback(_arr[i], i, _arr)) { return i; } } return -1;};const array1 = [5, 12, 8, 130, 44];const isLargeNumber = (element) => element > 13;console.log(array1.newFindlastIndex(isLargeNumber));// 4

The above code is very similar to the forward search, but only changes the conditions of the traversal.

1.3 Merge findIndex and findLastIndex

As you can see, except for the different conditions of the loop, the two methods are almost identical. Referring to lodash, we will simplify the two methods

/** * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [fromRight] 从右向左查找 * @returns {number} 返回第一个符合条件元素的下标或-1 */function baseFindIndex(array, predicate, fromRight) { const { length } = array; let index = fromRight ? length : -1; // 确定下标的边界 while (fromRight ? index-- : ++index

Let's take a look at its brother -

underscore

The idea is to use the different parameters passed to return different functions.

function createIndexFinder(dir) { return function(array, predicate, context) { const { length } = array; var index = dir > 0 ? 0 : length - 1; for (; index >= 0 && index About findIndex We’ve come to an end~ Let’s take a look at new scenarios and implementations! 

JavaScript Topic 9: Find the specified element in the array2. sortIndex

Find the position corresponding to value

in a sorted array, That is to ensure that after inserting into the array, it will still remain in an ordered state.

const arr = [1, 3, 5];sortedIndex(arr, 0); // 0// 不需要插入arr
So how to achieve this?2.1 Traversal

Everyone can think of traversal, although it is not necessarily the optimal solution:

function sortIndex(array, value) { for (let i = 0; i value) { return i; } } return array.length;}

2.2 Dichotomy

function sortIndex(array, value) { let low = 0, high = array.length; while (low 

3. indexOf and lastIndexOf

indexOf()
    : Return the
  • firstindex in the array where a given element can be found, if it does not exist Returns -1. Search from the front of the array backward, starting from fromIndex.lastIndexOf()
  • : Returns the index of the
  • lastof the specified element in the array, or -1 if it does not exist. Search forward from the back of the array, starting from fromIndex.3.1 The first version of implementation of indexOf
function indexOf(array, value) { for (let i = 0; i emmmm...After seeing the implementation of findIndex and lastFindIndex, indexOf should also be neat and tidy~

3.2 IndexOf and lastIndexOf General Version 1

Create different search methods through parameters

function createIndexOf(dir) { return function(array, value) { let index = dir > 0 ? 0 : arr.length - 1; for (; index >= 0 && index
3.3 IndexOf and lastIndexOf General Version 2

This time, we allow specified searches Position, let's take a look at the function of fromIndex:

Set the position to start searching. If the index value is greater than or equal to the array length, it means that the search will not be performed in the array and -1 will be returned.

If the index value provided in the parameter is a negative value, it is used as an offset from the end of the array, that is, -1 means starting to search from the last element, -2 means starting from the second to last element, so analogy.
Note: If the index value provided in the parameter is a negative value, the array will still be queried from front to back. If the offset index value is still less than 0, the entire array will be queried. Its default value is 0.


function createIndexOf(dir) { return function(array, value, fromIndex) { // 设定开始查找的位置。如果该索引值大于或等于数组长度,意味着不会在数组里查找,返回 -1。 let length = array == null ? 0 : array.length; let i = 0; if (!length) return -1; if (fromIndex >= length) return -1; if (typeof fromIndex === "number") { if (dir > 0) { // 正序 // 起始点>=0,沿用起始点,否则起始点为从后向前数fromIndex i = fromIndex >= 0 ? fromIndex : Math.max(length + fromIndex, 0); } else { // 倒序 // 起始点>=0,沿用起始点,否则起始点为从后向前数fromIndex length = fromIndex >= 0 ? Math.min(fromIndex + 1, length) : fromIndex + length + 1; } } // 起始下标 for ( fromIndex = dir > 0 ? i : length - 1; fromIndex >= 0 && fromIndex 
Writing this, we have finished searching for elements in the array. There is still a big difference between our own implementation and loadsh
or

underscore. If If you have any better implementation of the code in the above three sections, please be sure to write it in the message area~

JavaScript Topic 9: Find the specified element in the array

Related free learning recommendations:

javascript(Video)

The above is the detailed content of JavaScript Topic 9: Find the specified element in the array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete