In our daily development, we deal with the interface most, the front end by accessing the back-end interface, and then the interface data secondary processing rendering into the page. The process of secondary processing is to test whether the Coder is familiar with the Array and which method is the best in which scenario. Xiaobian encountered Array problems in recent development. When dealing with complex business requirements, I did not expect Array to have similar methods. Then I combined the methods to solve the current problem. It took me a week to finish the article in my off-duty time. After reading it, I received the most support from the likes and forwarding.


Iterate over the array method

Does not change the traversal method of the original array

forEach()

The forEach() method executes the given function once forEach item in the array, in ascending order.

grammar

Arr. ForEach (currentValue, index, array) thisArgCopy the code
  • currentValue: Value of the current item in the array
  • index: Index of the current item in the array
  • arr: the array object itself
  • thisArg: This parameter is optional. When the callback function is executedcallbackWhen used asthisThe value of the.

Pay attention to

  • If you are usingArrow function expressionTo pass in the function argument,thisArgArguments are ignored because the arrow function is lexically boundthisValue.
  • forEachDoes not directly change the object on which it is called, but that object may becallbackThe function changes.
  • everyIt doesn’t change the original array.
// Anti-theft paste: wechat official number: ForEach (val =>{console.log(' value = ${val*2} ')}) console.log(' original array = ${arr} '); / / value is 4 / / / / value for 6 to 8 / / value of 2 / / value is 88 / / the original array is 2,3,4,1,44Copy the code

reduce()

Reduce () array element accumulator that returns a combined result value.

grammar

arr.reduce(callback(accumulator, currentValue, index, array), initialValue)
Copy the code
  • accumulator: accumulator, which defaults to the first value of an array element
  • currentValueThe current value:
  • index: Current element index Optional
  • array: Array Optional
  • initialValue: Initial value This parameter is optional

Reduce takes two arguments, a callback function and an initial value.

It has two values:

    1. When providing theinitialValueAt the initial value, thenaccumulatorThe value ofinitialValue , currentValueThe value ofArray first value
    1. When not providedinitialValueAt the initial value, thenaccumulatorIs the first value in the array,currentValueIs the second value.

Pay attention to

  • If the array is empty and is not suppliedinitialValueThe initial value is thrownTypeError .
  • If the array has an element and none is providedinitialValueOr provideinitialValueIf the array is empty, the unique value is returned and will not be executedcallbackCallback function.

sum

// Anti-theft paste: wechat official number: / const arr = [1, 2, 3, 4] const sum = Arr. Reduce ((Accumulator, currentValue) => Accumulator + currentValue, 10) console.log(sum) //20 // accumulator // currentValue = 10 //10 + 1 + 2 + 3 + 4 // When the callback function is first executed, accumulator and currentValue are two different values: // If initialValue is provided when reduce() is called, accumulator is initialValue and currentValue is the first value in the array. // If initialValue is not provided, accumulator takes the first value in the array and currentValue takes the second value in the array.Copy the code

Evaluates the value in an object

To accumulate the values contained in the array of objects, you must provide initial values so that each item passes through your function correctly.

/* * @description: * @author: @date: 2021-08-07 00:53:51 * @lasteditTime: 2021-08-07 00:53:51 * @LastEditors: Do not edit */ const data = [ { date: '2021-8-1', income: 200 }, { date: '2021-8-2', income: 400 }, { date: '2021-8-3', income: ${data.reduce(((pre,currentValue) => pre + currentValue.income,0)} '); // Total revenue: 900Copy the code

Convert a two-dimensional array to a one-digit array

Const array = [[1, 2], [3, 4]]. The console log (array. Reduce ((a, b) = > a.c oncat (b))); //[1, 2, 3, 4]Copy the code

find()

Find () returns an element object or an element value that meets certain criteria, otherwise undefined

grammar

arr.find((element,index,array), thisArg)
Copy the code
  • element: Current element
  • index: Current element index Optional
  • array: The array itself is optional
  • thisArg: Used when executing a callbackthisThe object. optional
Const data = [{name:' zhang ', article: 3}, {name:' wang ', article: 9}, {name:' Li ', article: 9}, {name:' Li ', article: 9}, {name:' Li ', article: 9} 10 } ] console.log(data.find(item => item.article > 9 )); // {name: 'laolli ', article: 10}Copy the code

findIndex()

FindIndex () returns the index of the first element in the array that meets the criteria, or -1 if there is none.

grammar

arr.findIndex((element,index,array), thisArg)
Copy the code
  • element: Current element
  • index: Current element index Optional
  • array: The array itself is optional
  • thisArg: Used when executing a callbackthisThe object. optional
Const arr = [22,33,44,55] console.log(arr.findindex (val => val > 33)); //2 console.log(arr.findIndex(val => val > 99)); / / 1Copy the code

key()

Key () returns a new Array Iterator containing the key for each index in the Array.

grammar

keys()
Copy the code

Pay attention to

  • If the array is empty, when the key is fetched, it will be added to the traversal queue.
const inputModal = [ { name:'' }, { age:'' }, {hobby: "}] for(const key of inputmodal.keys ()){console.log(key)} // 0 // 1 // 2 const arr = [1,2, 3] for(const key)  of arr.keys()){ console.log(key); } // 0 // 1 // 2 // 3 // object.keys () returns an array of the given Object's own enumerable properties // so Object.keys(arr) = ['0', '1', '3' ] for(const key of Object.keys(arr)){ console.log(key); } // 0 // 1 // 3Copy the code

values()

The values() method returns a new Array Iterator containing the value of each index of the Array.

grammar

arr.values()
Copy the code
const Color = ['red','yelloe','orange']
​
for(val of Color.values()){
    console.log(val);
}
// red
// yelloe
// orange
Copy the code



Returns a Boolean value

every()

Every determines whether all elements in an array meet certain conditions and returns a Boolean value

grammar

Arr. Every (currentValue, index, array), thisArg)Copy the code
  • currentValue: The current value of the array must be
  • index: Array Index of the current item Optional
  • arr: The array object itself is optional
  • thisArg: This parameter is optional. When the callback function is executedcallbackWhen used asthisThe value of the. optional

Pay attention to

  • Returns when all elements meet the criteriatrue
  • everyIt doesn’t change the original array.
  • If you pass an empty array, it returns anyway, okaytrue.
Const arr = [2,3,4,1,44] console.log(arr.every(val => val > 0)); //true console.log(arr.every(val => { val > 2 })) //falseCopy the code

some()

Some () is used to determine whether an array element meets a condition, and returns true as long as one element meets a condition.

grammar

Arr. Some (currentValue, index, array), thisArg)Copy the code
  • currentValue: The current value of the array must be
  • index: Array Index of the current item Optional
  • arr: The array object itself is optional
  • thisArg: This parameter is optional. When the callback function is executedcallbackWhen used asthisThe value of the. optional

Pay attention to

  • some()Is called without changing the array.
  • If you test with an empty array, in any case it returnsfalse.
  • some()During traversal, the element range is determined, and elements added during traversal are not added to the traversal sequence.
Const arr = [2,3,4,1,44] console.log(arr.some(val => val > 2)) //true console.log([].some(val => val > 2)); //false const newList = [11,22,33,44] console.log(newlist.some (val => {newlist.push (55) newlist.push (66) val > 55})); //false const newList = [11,22,33,44] console.log(newlist.some (val => {newlist.push (55) newlist.push (66) val > 55})); //falseCopy the code

Create a new array without changing the original array

filter()

Filter () is used to walk through the original array, filter the array elements that meet the conditions, and form a new array element.

grammar

Arr. Some (currentValue, index, array), thisArg)Copy the code
  • currentValue: The current value of the array must be
  • index: Array Index of the current item Optional
  • arr: The array object itself is optional
  • thisArg: This parameter is optional. When the callback function is executedcallbackWhen used asthisThe value of the. optional

Pay attention to

  • filterDoes not change the original array, it returns the filtered new array.
  • filter()During traversal, the element range is determined, and elements added during traversal are not added to the traversal sequence.
Const arr = [11,22,33,44,55,66] console.log(arr.filter(val => val > 44)) console.log(' ${arr} '); // [55,66] // the original array is 11,22,33,44,55,66Copy the code

map()

Map () creates a new array, the result of which is returned when each element in the array calls one of the provided functions.

grammar

Arr. map(Callback (currentValue, index, array), thisArg)Copy the code
  • currentValue: The current value of the array must be
  • index: Array Index of the current item Optional
  • arr: The array object itself is optional
  • thisArg: This parameter is optional. When the callback function is executedcallbackWhen used asthisThe value of the. optional

Pay attention to

  • mapThe original array itself is not modified
  • map()During traversal, the element range is determined, and elements added during traversal are not added to the traversal sequence.
Const arr = [1,2,3,4] console.log(arr.map(val => val*3)) // [3, 6, 9, 12] console.log(arr) // [1,2,3,4]Copy the code


An array of CRUD

Change the original array method

reverse()

The reverse() method reverses the position of the elements in the array and returns the array. The first element of the array becomes the last, and the last element of the array becomes the first. This method changes the original array.

Const arr = [1,2,3] console.log(arr.reverse(11,22,33)) //[3, 2, 1]Copy the code

sort()

The sort() method takes an in-place algorithm to sort and returns an array. The default sort order is to convert elements to strings and then compare their UTF-16 code unit value sequences

An in situ algorithm is an algorithm that converts input using auxiliary data structures. However, it allows a small amount of extra storage for auxiliary variables. When the algorithm is running, the input is usually overwritten by the output. The in place algorithm updates the input sequence only by replacing or swapping elements.

Const arr = [23,11,33,44,1] console.log(arr.sort()) //[1, 11, 23, 33, 44] const arr = [23,11,33,44,1000000000] console.log(arr.sort()) // [1000000000, 11, 23, 33,44]Copy the code

Remove elements

shift()

The shift() method removes the first element from the array and returns the value of that element. This method changes the length of the array.

grammar

arr.shift()
Copy the code

Pay attention to

  • The element removed from the array; Returns if the array is emptyundefined
Const data = [{id: 1, name: 'front end'}, {id: 2, name: 'back-end'}, {id: 3, name: 'mobile'}, {id: 4, name: 'embedded development'}, ] const deleObj = data. The shift () the console. The log (' = = = = = = = = = = = = = = remove the element after the = = = = = = = = = = = = = = = = = = = = = = "); console.log(data); The console. The log (' = = = = = = = = = = = = = = = = = remove elements after the = = = = = = = = = = = = = = = = = = = '); The console. The log (' = = = = = = = = = = = = = = = the deleted element = = = = = = = = = = = = = = = = = = = = = '); console.log(deleObj); The console. The log (' = = = = = = = = = = = = = = = = the deleted element = = = = = = = = = = = = = = = = = = = = '); / / = = = = = = = = = = = = = = remove the element after the = = = = = = = = = = = = = = = = = = = = = = / / / / / {id: 2, name: 'back-end'}, / / {id: 3, name: 'mobile'}, / / {id: 4, name: 'embedded development'} / / / / = = = = = = = = = = = = = = = = = remove the element after the = = = = = = = = = = = = = = = = = = = / / = = = = = = = = = = = = = = = the deleted element = = = = = = = = = = = = = = = = = = = = = / / {id: 1, name: 'front end'} / / = = = = = = = = = = = = = = = = the deleted element = = = = = = = = = = = = = = = = = = = =Copy the code

pop()

The pop() method removes the last element from the array and returns the value of that element. This method changes the length of the array.

The usage is similar to shift.

grammar

arr.pop()
Copy the code

Pay attention to

  • The element removed from the array; Returns if the array is emptyundefined
Const data = [{id: 1, name: 'front end'}, {id: 2, name: 'back-end'}, {id: 3, name: 'mobile'}, {id: 4, name: 'embedded development'}, ] const deleObj = data.pop() console.log(data); / / / / / {id: 1, name: 'front end'}, / / {id: 2, name: 'back-end'}, / / {id: 3, name: 'mobile'} / /] the console. The log (deleObj); // {id: 4, name: 'embedded'}Copy the code

splice()

The splice() method modifies an array by deleting or replacing existing elements or adding new ones in place, and returns the modified contents as an array. This method changes the original array.

grammar

array.splice(start,deleteCount, [item1,item2....] )Copy the code
  • start: Start index
  • deleteCount: Number of deletions Optional
  • [item1, item2...].; Add and replace elements added from the starting index, optional

Pay attention to

  • An array of deleted elements. If only one element is removed, an array containing only one element is returned. If no element is deleted, an empty array is returned.

  • If only the initial index position is passed, all element objects after the index are deleted

    Const data = [{id: 1, name: 'front end'}, {id: 2, name: 'back-end'}, {id: 3, name: 'mobile'}, {id: 4, name: 'embedded development'}, ] data.splice(1) console.log(data) // [{id: 1, name: 'front-end'}]Copy the code

Starting with index 2, delete 1 array element object and add 2 array element objects

Const data = [{id: 1, name: 'front end'}, {id: 2, name: 'back-end'}, {id: 3, name: 'mobile'}, {id: 4, name: 'embedded development'}, ] data. Splice (2, 1,... [{id: 5, name: 'artificial intelligence'}, {id: 6, name: 'big data development'}]). The console log (data); / / / / / {id: 1, name: 'front end'}, / / {id: 2, name: 'back-end'}, / / {id: 5, name: 'artificial intelligence'}, / / {id: 6, name: }, // {id: 4, name: 'embedded'} //Copy the code

Add elements

splice()

It has been introduced above

push()

The push() method adds one or more elements to the end of an array and returns the array’s new length.

grammar

arr.push(element1, ... , elementN)Copy the code
Const data = [{id: 1, name: 'front end'}, {id: 2, name: 'back-end'},] the console. The log (data. Push ({id: 3, name: 'mobile'})) / / 3Copy the code

Merge array

Const data = [{id: 1, name: 'front end'}, {id: 2, name: 'back-end'},] var obj = [{id: 4, name: 'embedded development'}, ] // equivalent to data.push({id:4,name:' embedded development '}); Array.prototype.push.apply(data, obj); console.log(data); [{id: 1, name: 'front end'}, {id: 2, name: 'back-end'}, {id: 4, name: 'embedded development'}]Copy the code

unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the array’s new length.

Const arr = [1,2,3] console.log(arr.unshift(11,22,33)) //6 console.log(arr) //[11,22,33, 1,2,3]Copy the code

Do not change the original array element method

indexOf()

The indexOf() method returns the first index that can be found in the array for a given element, or -1 if none exists.

grammar

indexOf(searchElement)
indexOf(searchElement, fromIndex)
Copy the code
  • SearchElement: The element to find

  • FromIndex: Finds the first index of the specified element that appears by the specified index. optional

    • Returns -1 if the index is greater than or equal to the length of the array
    • If the supplied index is negative, it is treated as an offset from the end of the array
    • If the supplied index is negative, the array is still searched from front to back
    • If the supplied index is 0, the entire array is searched.
    • Default: 0 (searches the entire array).
Const arr = [1,1,2,3,4,5,4,4,6] console.log(arr.indexof (3)); //3 console.log(arr.indexOf(9)); / / - 1 the console. The log (arr. IndexOf (3, 4)); // select * from the element whose index is 4Copy the code

Array to heavy

Create a new empty array and use indexOf to determine if the empty array has an element for the first time.

  • If not, return [< 0],pushInto an empty array.
const newArr = [] arr.forEach(val => { if(newArr.indexOf(val) < 0){ newArr.push(val) } }) console.log(newArr); // [1, 2, 3, 4, 5, 6]Copy the code

lastIndexOf()

LastIndexOf () finds the index of the last occurrence of an element in the array, returning -1 if not found.

Returns -1 if none exists. Look forward from the back of the array, starting at fromIndex.

grammar

arr.lastIndexOf(searchElement, fromIndex)
Copy the code
  • SearchElement: The element to find

  • FromIndex: Finds the first index of the specified element that appears by the specified index. optional

    • Lookup backwards from the specified index location
    • Default is the array length minus 1(arr.length - 1), that is, the entire array is searched.
    • If the value is greater than or equal to the length of the array, the entire array is searched.
    • If it is negative, the array will still be looked up backwards.
    • If the value is negative and its absolute value is greater than the array length, the method returns -1, meaning that the array is not found.

Pay attention to

  • lastIndexOfUsing theStrictly equal= = =searchElementAnd the elements in the array.
Const arr = [1,1,2,3,4,5,4,4,6] console.log(arr.lastindexof (4)); / / 7 console. The log (arr. LastIndexOf (4, 11)); Console. log(arr.lastIndexof (4,-33))); // If the index specified by -1 is negative and the absolute value is greater than the array length, -1 console.log(arr.lastIndexof (4,-5)) is returned; //4 If the specified index is negative and the absolute value is less than the length of the array, the lookup will be carried forwardCopy the code

inCludes()

The includes() method is used to determine whether an array contains a specified value, returning true if it does and false otherwise.

grammar

arr.includes(searchElement, fromIndex)
Copy the code
  • SearchElement: The element to find

    Lookup is case sensitive

  • FromIndex: Finds the first index of the specified element that appears by the specified index. optional

    • Searches from the specified index
    • If it is negative, the value is in ascending order fromarray.length + fromIndexIndex began to search
    • iffromIndexIs greater than or equal to the length of the arrayfalseAnd the array will not be searched.
    • The default is 0
Const arr = [1,1,2,3,4,5,4,4,6] console.log(arr.includes(4)); / / true on the console. The log (arr. Includes,66 (4)); //false console.log(arr.includes(1,-1)); //falseCopy the code

concat()

The concat() method is used to merge two or more arrays.

grammar

var new_array = old_array.concat([arr1][arr2])
Copy the code

Pay attention to

  • The concat method does not alter this or any of the arrays supplied as arguments, but returns a shallow copy containing a copy of the same elements combined with the original array

    • Object references (rather than actual objects) :concatCopy the object reference into the new array. Both the original and new arrays refer to the same object. That is, if the referenced object is modified, the change is visible to both the new array and the original array. This includes elements that are also array parameters of arrays.
    • Data types such as strings, numbers, and booleans (noString.NumberandBoolean) Object) :concatCopies the string and number values into the new array.
Let arr1 = [1,2,3] let arr2 = [4,5,6] let arr3 = [[1,2],[3,4]] console.log(arr1.concat(arr2)); //[1, 2, 3, 4, 5, 6] // Merge console.log(arr1.concat(arr2).concat(arr3)); // [1, 2, 3, 4, 5, 6, [1, 2], [3, 4 ] ] let obj1 = [{a:1},{b:2}] let obj2 = [{c:3},{d:4}] let obj3 = obj1.concat(obj2) console.log(obj3); Console.log (obj3); //[{a: 1}, {b: 2}, {c: 3}, {d: 4}] obj1[0]. //[ { a: 4 }, { b: 2 }, { c: 3 }, { d: 4 } ]Copy the code

toString()

ToString () returns a string representing the specified array and its elements.

It is called automatically when an array is used as a text value or when a string concatenation operation is performedtoStringMethods.

For array objects, the toString method concatenates the array and returns a string containing each array element separated by a comma.

grammar

arr.toString()
Copy the code
Const arr = [1,2,3] console.log(arr.tostring ()); / / 1, 2, 3Copy the code

join()

The join() method returns a string by joining array elements separated by commas or the specified delimiter string.

If the array has only one entry, the entry is returned without a delimiter.

grammar

join()
join(separator)
Copy the code
  • separator: Specifies the split character optional
const arr = ['2021','08','08'] console.log(arr.join()); / / 2021,08,08 console. The log (arr. Join (' - ')); //2021-08-08 console.log(arr.join('/')); / / 2021/08/08Copy the code

slice()

The slice() method returns a new array object that is a shallow copy (including begin, but not end) of the array determined by begin and end. The original array will not be changed.

grammar

arr.slice(begin, end)
Copy the code
  • Begin: Specifies the start index for interception. Optional

    • The value starts from 0 by default
    • ifbeginIs negative, the interception starts with the absolute value from the end of the arrayslice(-2)The second element at the end
    • ifbeginBeyond the index range of the original array, an empty array is returned.
  • End: Specifies the end index to intercept optional

    • ifendIs omitted, thensliceIt will fetch all the way to the end of the original array.
    • ifendGreater than the length of the array,sliceIt will also fetch all the way to the end of the original array.
    • ifendIs negative, which indicates the penultimate element in the original array at which the extraction ends.
Const arr = [11,22,33,44,55,66,77,88] console.log(arr.slice(1,4)); //[22, 33, 44] console.log(arr.slice(-4,2)) //[] console.log(arr.slice(-4)); //[ 55, 66, 77, 88 ] console.log(arr.slice(0,-1)); // [// 11, 22, 33, 44, // 55, 66, 77 //]Copy the code

reference

Array – JavaScript | MDN

The last

The article spent a week after work, so it is not easy to write. The content of the article is referred to MDN documents. If you like, you can like 👍👍👍 to pay attention, support, I hope you can read this article to harvest!