Share four examples of incorrect use of JavaScript array methods
When I first learned JavaScript, I didn’t study it in depth and had only a limited understanding of some knowledge. In the past period of time, these 4 mistakes were made in all the pull requests I checked. Another reason I wrote this article is that I’ve made these mistakes myself. Let’s see how to use them correctly!
1. Don't use Array.indexOf, use Array.includes
"If you want to find an element in an array, use Array.indexOf!". I remember this sentence when I was studying JavaScript courses. This sentence is correct, it can indeed be used in this way!
According to the MDN document: "Array.indexOf will return the subscript of the first matching position of the element being searched for." Therefore, if this index needs to be used later, Array.indexOf is a good solution. However, the problem we want to solve is: find whether an array contains an element. This is a Yes/No question, a true or false question that returns a Boolean type. Therefore, I recommend using Array.includes, which returns a boolean value.
'use strict'; const characters = [ 'ironman', 'black_widow', 'hulk', 'captain_america', 'hulk', 'thor', ]; console.log(characters.indexOf('hulk')); // 2 console.log(characters.indexOf('batman')); // -1 console.log(characters.includes('hulk')); // true console.log(characters.includes('batman')); // false
2. Don’t use Array.filter, use Array.find
Array.filter is a very useful function that returns a new array that meets the filtering conditions . As its name implies, it is used for filtering.
However, if we know that the result we want has only one element, I do not recommend using it. For example, if our callback function definition uses a unique ID to filter, then the result must be unique. In this case, Array.filter will return an array with only one element. Because since we can search by a specific ID, we have already determined that there is only one element, so using an array makes no sense.
In addition, let’s talk about performance issues. In order to return all matching elements, Array.filter needs to search the entire array. You can imagine that if there are hundreds of elements that meet the filtering conditions, the returned array will be very large.
To avoid this situation, I recommend using Array.find. It only returns the first element that satisfies the filter condition. Moreover, Array.find will end execution after finding the first element that meets the condition, instead of searching the entire array.
'use strict'; const characters = [ { id: 1, name: 'ironman' }, { id: 2, name: 'black_widow' }, { id: 3, name: 'captain_america' }, { id: 4, name: 'captain_america' }, ]; function getCharacter(name) { return character => character.name === name; } console.log(characters.filter(getCharacter('captain_america'))); // [ // { id: 3, name: 'captain_america' }, // { id: 4, name: 'captain_america' }, // ] console.log(characters.find(getCharacter('captain_america'))); // { id: 3, name: 'captain_america' }
3. Don’t use Array.find, use Array.some
I admit that I have made many mistakes. Later, a very good friend asked me to read the MDN documentation and said that there was a better solution. This situation is very similar to the Array.indexOf/Array.includes just mentioned.
In the previous example, we saw that Array.find accepts a filter function and returns satisfied elements. So, if we want to find whether an array contains a certain element, is Array.find the best solution? Probably not, because it returns the element-specific value, not a boolean value.
I recommend everyone to use Array.some, which will return a Boolean value.
'use strict'; const characters = [ { id: 1, name: 'ironman', env: 'marvel' }, { id: 2, name: 'black_widow', env: 'marvel' }, { id: 3, name: 'wonder_woman', env: 'dc_comics' }, ]; function hasCharacterFrom(env) { return character => character.env === env; } console.log(characters.find(hasCharacterFrom('marvel'))); // { id: 1, name: 'ironman', env: 'marvel' } console.log(characters.some(hasCharacterFrom('marvel'))); // true
4. Don’t use Array.map and Array.filter combination, use Array.reduce
Array.reduce is a bit difficult to understand! However, if we use Array.filter and Array.map at the same time every time, do you realize that you need something, right?
What I mean is: we looped through the entire array 2 times. The first time is to filter and return a new array, and the second time to construct a new array through map. We use two array methods, each with its own callback function, and the array returned by Array.filter is never used again.
To avoid inefficiency, I recommend using Array.reduce. Same result, more elegant code! Please see the example below:
'use strict'; const characters = [ { name: 'ironman', env: 'marvel' }, { name: 'black_widow', env: 'marvel' }, { name: 'wonder_woman', env: 'dc_comics' }, ]; console.log( characters .filter(character => character.env === 'marvel') .map(character => Object.assign({}, character, { alsoSeenIn: ['Avengers'] })) ); // [ // { name: 'ironman', env: 'marvel', alsoSeenIn: ['Avengers'] }, // { name: 'black_widow', env: 'marvel', alsoSeenIn: ['Avengers'] } // ] console.log( characters .reduce((acc, character) => { return character.env === 'marvel' ? acc.concat(Object.assign({}, character, { alsoSeenIn: ['Avengers'] })) : acc; }, []) ) // [ // { name: 'ironman', env: 'marvel', alsoSeenIn: ['Avengers'] }, // { name: 'black_widow', env: 'marvel', alsoSeenIn: ['Avengers'] } // ]
The above is the detailed content of Share four examples of incorrect use of JavaScript array methods. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The method of using a foreach loop to remove duplicate elements from a PHP array is as follows: traverse the array, and if the element already exists and the current position is not the first occurrence, delete it. For example, if there are duplicate records in the database query results, you can use this method to remove them and obtain results without duplicate records.

Methods for deep copying arrays in PHP include: JSON encoding and decoding using json_decode and json_encode. Use array_map and clone to make deep copies of keys and values. Use serialize and unserialize for serialization and deserialization.

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values takes a relatively long time.

Multidimensional array sorting can be divided into single column sorting and nested sorting. Single column sorting can use the array_multisort() function to sort by columns; nested sorting requires a recursive function to traverse the array and sort it. Practical cases include sorting by product name and compound sorting by sales volume and price.

The best practice for performing an array deep copy in PHP is to use json_decode(json_encode($arr)) to convert the array to a JSON string and then convert it back to an array. Use unserialize(serialize($arr)) to serialize the array to a string and then deserialize it to a new array. Use the RecursiveIteratorIterator to recursively traverse multidimensional arrays.

PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group.

The PHP array merging and deduplication algorithm provides a parallel solution, dividing the original array into small blocks for parallel processing, and the main process merges the results of the blocks to deduplicate. Algorithmic steps: Split the original array into equally allocated small blocks. Process each block for deduplication in parallel. Merge block results and deduplicate again.

PHP's array_group() function can be used to group an array by a specified key to find duplicate elements. This function works through the following steps: Use key_callback to specify the grouping key. Optionally use value_callback to determine grouping values. Count grouped elements and identify duplicates. Therefore, the array_group() function is very useful for finding and processing duplicate elements.
