Using a bad array program ape is not a good ape, I said ~

A big reason is that the array method is not proficient, resulting in a lot of junk code, in fact, a lot of things can be simple, efficient and elegant with a little change. So HERE I summarize the common methods of array and kit Kat (kit Kat is mainly reduce~).

The first thing to remember about arrays is that splice, sort, and reverse operate on the array itself. Other ways to change yourself are to add or remove push/pop/unshift/shift, fill fill, and copy fill copyWithin.

Common methods of using arrays are discussed first.

Common methods for arrays

Keys (), array.values (), and array.entries () :

Generate arrays like [1-100] :

When testing an array with a large amount of data, it can be generated like this:

// fill const arr = new Array(100).fill(0).map((item, Index) => index + 1) // array. from() const arr = array. from(Array(100), (v, k) => k + 1) // + array.keys() const ary = [... array (100).keys()Copy the code

New Array(100) generates an Array with 100 empty Spaces, which cannot be traversed by map(), forEach(), filter(), reduce(), every(), some() because empty Spaces are skipped (for of does not skip empty Spaces, Can be traversed). […new Array(4)] You can set the default value undefined for the empty space so that the Array can be traversed by the above method.

Array destruct assignment application

/ / exchange variables [a, b] = [b, a] [o.a onychoteuthis] = [onychoteuthis, o.a] / / generates residual const array [rest] a,... = 'asdf' [...] / / a: 'a', the rest: ["s", "d", "f"] Copies the codeCopy the code

Array shallow copy

Const arr = [1, 2, 3] const arrClone = [...arr] const obj = {a: 1} const objClone = {... Obj} copies the codeCopy the code

Slice (0, arr.length)/ aror.from (arr), etc. After the operator, you won’t want to use anything else

An array of merger

Const arr1 = [1, 2, 3] const arr2 = [4, 5, 6] const arr3 = [7, 8, 9] Const arr = [...arr1,...arr2,...arr3] copy codeCopy the code

Arr1. concat(arr2, arr3) can also merge, but with… After the operator, you won’t want to use anything else

Array to heavy

Const arr = [1, 1, 2, 2, 3, 4, 5, 5] const newArr = [...new Set(arr)] copy codeCopy the code

New Set(ARR) takes an array argument and generates a data type of Set structure. The elements of the set data type are not duplicated and are Array iterators, so you can use this feature to de-duplicate.

Array intersection

const a = [0, 1, 2, 3, 4, 5] const b = [3, 4, 5, 6, 7, 5] const duplicatedValues = [...new Set(a)]. Filter (item => b.icludes (item)) duplicatedValues //Copy the code

Array takes the difference set

const a = [0, 1, 2, 3, 4, 5] const b = [3, 4, 5, 6, 7, 8] const diffValues = [...new Set([...a, ...b])].filter(item => ! b.includes(item) || ! A. includes(item)) // [0, 1, 2, 6, 7, 8] copy codeCopy the code

Array to object

const arr = [1, 2, 3, 4] const newObj = {... arr} // {0: 1, 1: 2, 2: 3, 3: 4} const obj = {0: 0, 1: 1, 2: 2, length: Let newArr = [...obj] // Uncaught TypeError: Object is not iterable... Array.form() lets newArr = array.from (obj) // [0, 1, 2] copy codeCopy the code

An array of flat

Const obj = {a: 'group ', b:' group ', c: 'group ', d: } const getName = function (item) {return item.includes(' group ')} // const flatArr = Object.values(obj).flat().filter(item => getName(item)) Const flatArr = object.values (obj).flat().filter(getNameCopy the code

Use array.flat() for two-dimensional arrays and array.flatmap () for three-dimensional and larger arrays. Array. flat(2) can be passed a number such as 2 to indicate the number of layers to be flattened.

Arrays are often traversed

Array traversal is commonly used by forEach, every, some, filter, Map, reduce, reduceRight, find, findIndex and other methods, and many methods can achieve the same effect. Array methods not only have to work, they have to work well. To use it well, you need to know when and how to use it.

Hybrid use of traversal

The filter and map methods return an array, so they can be mixed with other array traversal methods. Note that the more traversal, the lower the efficiency

const arr = [1, 2, 3, 4, 5] const value = arr .map(item => item * 3) .filter(item => item % 2 === 0) .map(item => item + 1) .reduce((prev, Curr) => prev + curr, 0) copy codeCopy the code

Checks whether all elements of the array match the criteria

Every (item => typeof item === = 'number') copies codeCopy the code

Checks if any elements in the array match the criteria

Const arr = [1, 2, 3, 4, 5] const hasNum = arr.some(item => typeof item === 'number') copies codeCopy the code

Find the first element/subscript that meets the criteria

const arr = [1, 2, 3, 4, 5] const findItem = arr.find(item => item === = 3) // Returns the subindex of the child const findIndex = arr.FindIndex (item => item === 3) // Returns the subindex of the child 😂 let findIndex arr.find((item, index) => {if (item === 3) {findIndex = index}}) copy codeCopy the code

Error in Using arrays

There are many methods for arrays, and many can achieve the same effect, so use the appropriate method according to your requirements.

A large part of the junk code is caused by the improper use of arrays in common ways. Here are some points to be aware of:

Array. Includes () and array. IndexOf ()

Array.includes () returns a Boolean value, and array.indexof () returns the indexOf the array’s subitems. IndexOf must be used only when an index value is required.

Const arr = [1, 2, 3, 4, 5] const index = arr.indexof (1) // 0 if (~index) {// If index === -1, ~index = 0; If index is not -1, ~index is non-0. Arr. Spilce (index, 1)} // if you use indexOf, there is no need to use the index. // If you use indexOf, there is no need to use the index. const isExist = arr.includes(6) // true if (! IsExist) {arr.push(6)} copies the codeCopy the code

If array.indexof () is not found, return -1. If array.includes() is found, return true

[NaN].includes(NaN) // true [NaN].indexof (NaN) // -1 Copy codeCopy the code

Array.find (), array.findIndex(), and array.some()

Array.find () returns the first eligible subitem, array.findIndex() returns the index of the first eligible subitem, and array.some() returns true if there is a compound condition, false if there is no compound condition. Note that all three are short-circuited operations, that is, they do not continue traversal after finding the one that matches the condition.

Array.find () is used when an array’s children are needed; Array.findindex () is used when the index value of the subitem is needed; If you only need to know if there are any eligible children, use array.some().

Const arr = [{label: 'male ', value: 0}, {label:' female ', value: 1}, {label: 'male ', value: 1}, 2}] // use some const isExist = arr.some(item => item.value === 2) if (isExist) {console.log(' ha ha ha found ')} // use find const Item = arr.find(item => item.value === 2) if (item) {console.log(item.label)} // Use findIndex const index = arr.findIndex(item => item.value === 2) if (~index) { const delItem = arr[index] arr.splice(index, 1) console.log(' you deleted ${delitem.label} ')} copy codeCopy the code

It is recommended to use array.some() when only booleans are needed and when the array’s subitems are strings or numbers:

Const arr = [0, 1, 2, 3, 4] // Correct const isExist = arr.some(item => item === 0) if (isExist) {console.log(' console.log ') Const isExist = arr.find(item => item === 0) if (isExist) {// isExist is 0, Const arr = [", 'asdf', 'qwer', const arr = [", 'asdf', 'qwer', Const isExist = arr.some(item => item === ") if (isExist) {console.log(' there is a subitem to look for, Const isExist = arr.find(item => item === ") if (isExist) {// isExist is now ", The implicit conversion to Boolean is false console.log(' cannot execute here ~')} copy codeCopy the code

Array. The find () and array. The filter ()

The only thing you need to know is that array.filter() returns an array of all eligible children and iterates through all the arrays; Array.find () returns only the first eligible child, which is a short-circuit operation. No more examples ~

Use Set data structures wisely

Because ES6 provides a Set data structure natively, and Set can ensure that the subitems are not repeated, and it is very convenient to convert with Array, Set can be directly used to replace Array in some scenarios that may involve repeated addition, avoiding repeated judgment of whether the subitem already exists in multiple places.

const set = new Set()
set.add(1)
set.add(1)
set.add(1)
set.size // 1
const arr = [...set] // arr: [1]
Copy the code

Powerful Reduce (Kit Kat)

Array.reduce traverses and takes the return value of the current callback function as the first argument to the next callback function execution.

Using array.reduce to replace scenarios that require multiple traversal can greatly improve code efficiency.

  1. usingreduceOutput a number/string

If you have the following array arr where each element consists of the letter ‘s’ plus a number, find the largest number in the array :(arr is not empty)

Const arr = [' s0 ', 's4', 's1' and s2 ', 'the s8', 'the s3'] / / 1 repeated traversal method, Inefficient const newArr = arr.map(item => item.substring(1)).map(item => Number(item)) const maxS = math.max (... Const maxS = arr. Reduce ((prev, cur) => {const curIndex = Number(cur.replace('s', '')) return curIndex > prev ? CurIndex: prev}, 0) Copy the codeCopy the code
  1. usingreduceOutput an array/object
// const arr = [1, 2, 3, 4, 5] // Const value = arr.filter(item => item % 2 === 0).map(item => ({value: Const value = arr. Reduce ((prev, curr) => {return curr % 2 === 0? [...prev, {value: curr}] : prev}, []) Copy codeCopy the code

Master the above two usages, combined with the actual needs, you can use reduce/reduceRight to achieve a variety of Kitkat sex skills.

Example: Use reduce to generate the desired HTML string by doing the following:

Const data = {'if _ then s9': [' an effect is of any kind, a structure is of a dwelling, a structure can withstand an effect, an effect is likely to occur in the course of normal construction and normal use ', 'An action is a variety, a structure is a dwelling, a structure can withstand an action, an action is likely to occur in the course of normal construction and normal use'], 'if C then S4 ': [' Where conditions permit, structural members shall meet requirements for safety, suitability and durability ', ]} const ifthens = object.entries (data).reduce((prev, cur) => { const values = cur[1].reduce((prev, cur) => `${prev}<p>${cur}</p>`, '') return ` ${prev} <li> <p>${cur[0]}</p> ${values} </li> ` }, ) const HTML = '<ul class=" nLP-notify-body "> ${ifthens} </ul>' copy codeCopy the code

The generated HTML structure is as follows:

<ul class=" nLP-notify-body "> <li> < P >if _ then S9 </p> </p> <p> action belongs to various, structure belongs to residence, structure can withstand action, action belongs to may occur in normal construction and normal use process </p> < P > <li> <p> action belongs to normal construction and normal use process </p> <li> <p>if C Then S4 </p> <p> When conditions are available, the structural members meet the requirements, requirements are safety, suitability and durability </ P > </ LI > </ul> Copy codeCopy the code

Here’s another trick to replace the reverse function

Because the array.reverse() function changes the original array itself, this limits some usage scenarios. What if I want a reverse function that doesn’t change the array itself? Take away!

const myReverse = (arr = []) => { return arr.reduceRight((prev, cur) => [...prev, cur], []) // You can also return a comma expression (prev.push(cur), prev)} copy codeCopy the code

Reduce is so powerful that I can only show you the basics here. 25 Advanced Uses of Array Reduce you Need to Know

Link: juejin.cn/post/684490… The copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.