"How to better use JavaScript arrays"

Source: Internet
Author: User
Tags unique id

Read this article hurriedly, I promise, over the last few months I, I'm sure I made 4 mistakes on array issues. So I write this article and read this article to make it easier for you to use JavaScript arrays in some way

Replacing Array.indexof with Array.includes

"If you're searching for an element in an array, use Array.indexof," I remember seeing this sentence when I was learning JavaScript, which is certainly true.

The MDN document describes this as Rray.indexof "returns the index of the first searched element, so if you want to search for the subscript of an element, then array.indexof can solve it well."

However, if we want to see if an array includes an element, how to do it. Just like yes/no, this is the Boolean value. Here we recommend using the Array.includes method that returns a Boolean value.

const persons = ["jay","leinov","jj","nico"];console.log(persons.indexOf("leinov"));// 1console.log(persons.indexOf("beyond"));// -1 console.log(persons.includes("leinov"));// trueconsole.log(persons.includes("beyond"));// false
Use Array.find instead of Array.filter

Array.filter is a very useful way to create a new array from the callback parameters of an array, as his name suggests, and we use it to filter out a shorter array

But if we know for sure that the callback function returns only one item in the array, then I wouldn't recommend using him, for example, when the callback parameter used to filter is a unique ID, in which case, Array.filter returns a new array of inclusions for this item. Looking for a special ID, we want to take only one item, and the returned array is useless.

Next we look at performance, in order to return each item that matches the callback function, Array.filter must retrieve the entire array, and let's imagine that we have hundreds of items that satisfy our callback parameter function, and the array we filter is very large.

To avoid this, I recommend Array.find , who, like Array.filter, needs a callback function parameter and returns the first item that satisfies the callback function parameter. And Array.find stops filtering after the filter is satisfied, the entire array is not retrieved.

use strict';const singers = [  { id: 1, name: '周杰伦' },  { id: 2, name: '李建' },  { id: 3, name: '庾澄庆' },  { id: 4, name: '谢霆锋' },  { id: 5, name: '周杰伦' },];function getSinger(name) {  return signer => signer.name === name;}console.log(singers.filter(getSinger('周杰伦')));// [//   { id: 1, name: '周杰伦' },//   { id: 5, name: '周杰伦' },// ]console.log(characters.find(getSinger('周杰伦')));// { id: 1, name: '周杰伦' }
Use Array.some instead of Array.find

I admit that I often make mistakes on this, and then a good friend of mine reminds me to look at the MDN document to find a better way to solve it, which is very similar to the array.indexof/array.includes above.

As mentioned earlier, Array.find requires a callback function as a parameter to return a satisfied element. If we need to know if an array has a value, Array.find is the best way to do it. Maybe not, because the return is a value, not a Boolean value.

In this case, I recommend using Array.some, which returns a Boolean value that satisfies the callback parameter

'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
Use Array.reduce instead of Array.filter and Array.map

Let's take a look at Array.reduce,array.reduce is not very well understood, but if we do array.filter,array.map feel like we missed something.

I mean, we retrieved the array two times, first filtered and created a short array, and the second created a new inclusion of the array that we filtered to get to. In order to get the results we used two array methods, each with a callback function and an array, where a array.filter created by us is not available.

To avoid this performance problem, I recommend using Array.reduce instead. The same result, the better code. Aaray.reduce allows you to filter and add items that are satisfied to the accumulator. For example, this accumulator can be a numeric increment, an object to be populated, a string, or an array.

In our previous example, we have been using Array.map, so I recommend using Array.reduce to concatenate arrays using accumulators. In the following example, depending on the value of env, we will either add it to the accumulator or leave the accumulator as its original value.

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

Original: Here's how to make better use of JavaScript arrays
If there is a translation error please refer to 3Q

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.