Home > Web Front-end > JS Tutorial > body text

How can newbies use arrays better in JavaScript? (source code)

云罗郡主
Release: 2018-10-11 16:03:35
forward
1984 people have browsed it

The content of this article is about how newbies can better use arrays in JavaScript? (Source code), it has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Use Array.find instead of Array.filter

Array.filter is a very useful method. It filters the original array through the callback function and returns the filtered items as a new array. As its name suggests, we use this method for filtering, which (generally speaking) results in a new array with a shorter length.

However, if you know that after filtering by the callback function, only the only item will remain, then I do not recommend using Array.filter. For example: use equal to a unique ID as the filter condition to filter an array. In this example, Array.filter returns a new array with only one item. However, since we are just trying to get the item with a specific ID, this new array is useless.

Let’s discuss performance. In order to get all items that match the callback function's filter criteria, Array.filter must traverse the entire array. If there are thousands of items in the original array, the callback function needs to be executed a considerable number of times.

To avoid these situations, I recommend using Array.find. It requires a callback function just like Array.filter, but only returns the first item that meets the criteria. When the first element that meets the callback function's filter conditions is found, it will immediately stop searching downwards. No more iterating through 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' }
Copy after login

Use Array.some instead of Array.find

I admit that I often make this mistake. Then a friend suggested I check out the MDN documentation to find a better way. In fact (this error) is very similar to the Array.indexOf/Array.includes example above.

In the above example, we know that Array.find requires a callback function as a parameter and returns the (qualified) first element. However, when we need to know if an element exists in an array, is Array.find the best choice? Not necessarily, since it returns an element, not a boolean.

In the example below, I recommend using Array.some, which returns the boolean value you need.

'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
Copy after login

Add the difference between the use of Array.some and Array.includes. Both return a Boolean value indicating whether an item exists in the array, and stop traversing the array once the corresponding item is found. The difference is that the parameter of Array.some is a callback function, while the parameter of Array.includes is a value (the second optional parameter is not considered).

Suppose you want to know whether the item with value exists in the array, you can either write code: [].includes(value), or you can pass in item => item === value to Array.some as a callback function. Array.includes is easier to use, and Array.some is more controllable.

Use Array.reduce instead of the combination of Array.filter and Array.map

In fact, Array.reduce is not easy to understand. However, if we first filter the original array using Array.filter and then call Array.map (on the result) (to get a new array). This seems to be a problem. Is there something we have overlooked?

The problem with this is: we traverse the array twice. The first time is to filter the original array to obtain a new array with a slightly shorter length. The second traversal (Translator's Note: Array.map) is to process the new array returned by Array.filter and create a new array again. ! To get the final result, we used a combination of two array methods. Each method has its own callback function, and the temporary array used by Array.map is provided by Array.filter, which (generally speaking) cannot be reused.

To avoid such inefficient scenarios, my suggestion is to use Array.reduce. Same results, better code! Array.reduce allows you to put filtered and reduced items into an accumulator. The accumulator can be a number to be incremented, an object to be filled, a string or array to be spliced, etc.

In the above example, we used Array.map, (but more) it is recommended to use Array.reduce where the accumulator is the array to be spliced. In the following example, depending on the value of the variable env, we will add it to the accumulator or leave the accumulator unchanged (i.e. do nothing).

'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'] }
// ]
Copy after login

The above is how newbies can better use arrays in JavaScript? (source code) full introduction, if you want to know more about JavaScript video tutorial, please pay attention to the PHP Chinese website.

The above is the detailed content of How can newbies use arrays better in JavaScript? (source code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:qdfuns.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template