Multiple ways to judge the existence of elements in an array by using JS ten minutes

  • 2021-11-01 02:04:35
  • OfStack

Preface

In front-end development, it is often encountered to judge whether an element exists in an array. In fact, there are many ways to judge. Let's understand them one by one.

Let's first define an array:


const arr = [
 13,
 false,
 'abcd',
 undefined,
 13,
 null,
 NaN,
 [1, 2],
 { a: 123 },
 () => Date.now(),
 new Date('2021/03/04'),
 new RegExp('abc', 'ig'),
 Symbol('sym'),
];

In this array, we include several types: number, boolean, string, undefined, null, array, object, Date, Symbol, and so on. The number 13 appears twice.

Come prepared

1. indexOf

We are most familiar with indexOf. After all, it appeared early, has good compatibility and is very convenient to use.

If the element exists, the index value of the first occurrence is returned; If the element does not exist in the whole array,-1 is returned.

1.1 Usage

As long as you judge whether the returned data is-1, you can know whether the array contains this element.


arr.indexOf(13) >= 0; // true, indexOf Return 0
arr.indexOf(2) >= 0; // false, indexOf Return -1

Corresponding to indexOf is lastIndexOf, which looks for elements from the last, and if there is this element, returns the index of the last one in the array; If the element does not exist,-1 is returned.


arr.lastIndexOf(13) >= 0; // true, lastIndexOf Return 4,  Finally 1 Secondary index 

When judging whether a variable exists, the two methods are called in the same way.

1.2 Second optional parameter

indexOf and lastIndexOf also have a second optional parameter, fromIndex, which indicates which index to start the search on.

In indexOf, if fromIndex exceeds the length of the array, it returns-1 directly, and if it is negative, it counts several indexes (arr. length-Math. abs (fromIndex) from the last to the front, and then starts searching backward.

In lastIndexOf, if fromIndex reaches or exceeds the length of the array, the whole array is searched; If it is negative, count several indexes (arr. length-Math. abs (fromIndex) from the last, and then start searching forward. If the absolute value of the negative number exceeds the length of the array, it will return-1 directly.


arr.indexOf(13, 2); // 4,  From index value 2 Start looking back, and find it first 13 The index value of is 4
arr.indexOf(13, -10); // 4,  From index value 1(11-10) Start retrieving backwards 
arr.lastIndexOf(13, 2); // 0,  From index value 2 Go ahead and start searching 
arr.lastIndexOf(13, -2); // 4,  From index value 9(11-2) Start searching forward 

Moreover, indexOf and lastIndexOf are judged in a strictly equal way (= = =).

arr. indexOf (null); //5. There are several false values false and undefined before null, and the index value of null can also be found accurately
Trembling

2. includes

indexOf is mainly used to find the index value of the element, but we can use the returned index value to indirectly judge whether the element exists in the array.

The includes method added in ES7 (ES2016) is specially used to judge whether elements exist or not. The return value is true or false, true means existence, false means nonexistence, which is simple and clear.


arr.includes(13); // true
arr.includes('abc'); // false
arr.includes(false); // true,  Existence false Element 

At the same time, there is a second optional parameter fromIndex in includes method, and the usage of fromIndex is the same as that of indexOf. If fromIndex exceeds the length of the array, it returns-1 directly. If it is negative, it counts several indexes from the last one (arr. length-Math. abs (fromIndex), and then starts searching backward.


arr.includes(13, 5); // false,  From index value 5 Began to retrieve backwards, but did not retrieve 

So far, we haven't judged the latter types, such as Array, Object, Date and Symbol. Let's now judge the following elements:


//  Use indexOf Judge 
arr.indexOf(NaN); // -1
arr.indexOf([1, 2]); // -1
arr.indexOf({ a: 123 }); // -1
arr.indexOf(() => Date.now()); // -1
arr.indexOf(new Date('2021/03/04')); // -1
arr.indexOf(new RegExp('abc', 'ig')); // -1
arr.indexOf(Symbol('sym')); // -1

//  Use includes Judge 
arr.includes(NaN); // false
arr.includes([1, 2]); // false
arr.includes({ a: 123 }); // false
arr.includes(() => Date.now()); // false
arr.includes(new Date('2021/03/04')); // false
arr.includes(new RegExp('abc', 'ig')); // false
arr.includes(Symbol('sym')); // false

The result is miserable, and none of these elements are retrieved in the array. But in fact, they are all real in the array.

This is because indexOf and includes are determined in a strictly equal way (= = =).


NaN === NaN; // false,  Two NaN It will never be equal 
[1, 2] === [1, 2]; // false,  Each declared array has a separate storage address 
{a: 123} === {a: 123}; // false,  Identical array 
new Date('2021/03/04')===new Date('2021/03/04'); // false,  Look at the date is the same, but use new If the objects come out for comparison, they must be unequal 
Symbol('sym')===Symbol('sym'); // Symbol Types are created to avoid conflicts, and the attributes in parentheses are only for convenience of description 

For these types that can't be retrieved, we need to write our own functions to judge the special types.

3. find and findIndex

find () and findIndex () allow us to customize the way we judge through callback functions.

3.1 find Method

The find () method returns the value of the first element in the array that satisfies the supplied test function. Otherwise undefined is returned.

The find () method cannot detect an undefined element in an array.

The find () method returns undefined because the undefined element does not exist and exists. Here we will consider other ways, and we will talk about them later.


arr.find((item) => item === 13); // 13,  Element found 13
arr.find((item) => item === 3); // undefined,  Element not found 3
arr.find((item) => item === undefined); // undefined,  I don't know if I found it or not 

For the slightly more complicated types above, we need special judgments:


arr.find((item) => typeof item === 'number' && isNaN(item)); // NaN

// array And object Types, the situation is complicated because the type of each element cannot be determined 
//  If it is determined that they are all basic types, such as string, number, boolean, undefined, null And so on, you can turn it into a string and compare it again 
//  There are also many ways to turn strings, such as JSON.stringify(arr), arr.toString(), arr.split('|') Etc 
//  More complicated, only 1 Items 1 Item comparison, or use recursion 
arr.find((item) => item.toString() === [1, 2].toString()); // [1, 2]
arr.find((item) => JSON.stringify(item) === JSON.stringify({ a: 123 })); // {a: 123}
arr.find((item) => {
 if (typeof item === 'function') {
 return item.toString() === (() => Date.now()).toString();
 }
 return false;
}); // () => Date.now()
arr.find((item) => {
 if (item instanceof Date) {
 return item.toString() === new Date('2021/03/04').toString();
 }
 return false;
}); // Thu Mar 04 2021 00:00:00 GMT+0800
arr.find((item) => {
 if (item instanceof RegExp) {
 return item.toString() === new RegExp('abc', 'ig').toString();
 }
 return false;
}); // /abc/gi

// Symbol You really can't compare, you can only compare whether the description is 1 Sample 
arr.find((item) => {
 if (typeof item === 'symbol') {
 return item.toString() === Symbol('sym').toString();
 }
 return false;
}); // Symbol(sym)

The above judgment code will also be used in the following methods.

3.2 Compare the two elements

We compared the comparison of various types of elements above, and summarized them a little.

First, define a function:


arr.indexOf(13) >= 0; // true, indexOf Return 0
arr.indexOf(2) >= 0; // false, indexOf Return -1
0 3.2. 1 Basic types

For elements of basic types such as string, number, boolean, undefined, null, the comparison can be made directly:


arr.indexOf(13) >= 0; // true, indexOf Return 0
arr.indexOf(2) >= 0; // false, indexOf Return -1
1 3.2. 2 NaN data

NaN uses typeof to determine the number type, but NaN is not equal to any number, including itself.


arr.indexOf(13) >= 0; // true, indexOf Return 0
arr.indexOf(2) >= 0; // false, indexOf Return -1
2 3.2. 3 Function and Date and RegExp

These types can be compared by converting variables into strings:


const compare = (x, y) => {
 if (typeof x === 'number' && isNaN(x) && typeof y === 'number' && isNaN(y)) {
  return true;
 }
 if (
  (typeof x === 'function' && typeof y === 'function') ||
  (x instanceof Date && y instanceof Date) ||
  (x instanceof RegExp && y instanceof RegExp) ||
  (x instanceof String && y instanceof String) ||
  (x instanceof Number && y instanceof Number)
 ) {
  return x.toString() === y.toString();
 }
 return x === y;
};

For object type and array type, we can take each item apart, and then compare them one by one in the above way.

3.3 findIndex method

If we also want to determine whether undefined exists in the array, we can use the findIndex () method.

The findIndex () method returns the index of the first element in the array that satisfies the supplied test function. Returns-1 if no corresponding element is found.


arr.indexOf(13) >= 0; // true, indexOf Return 0
arr.indexOf(2) >= 0; // false, indexOf Return -1
4

The judgment of other data formats is the same as that of find () 1 above.

Rare visitors

4. some

The some () method tests whether at least one element in the array passes the function test provided. It returns a value of type Boolean.

Note: If you test with an empty array, it returns false in any case.

The some () method is used in the same way as the find () method, except that the some () method returns data of type boolean.


arr.indexOf(13) >= 0; // true, indexOf Return 0
arr.indexOf(2) >= 0; // false, indexOf Return -1
5

5. filter

The filter () method creates a new array that contains all the elements of the test implemented through the provided function.

The filter () method returns an array of elements, no matter how many elements are found or no elements are found, and the data in the array is the element we want.


arr.indexOf(13) >= 0; // true, indexOf Return 0
arr.indexOf(2) >= 0; // false, indexOf Return -1
6

Therefore, we can judge whether the original array contains the elements we want by the length of the array.

Slightly

6. Summary

There are many ways to find the elements in an array. We can choose the more appropriate way by the format of the elements in the array. If they are all basic types, it is recommended to use includes () method first. If the format is complex, it is recommended to use some () method. Both methods return the boolean type directly, and the result of the method can be used directly without any more conversion.


Related articles: