Summary of Practical Methods of Array Processing for JS Beginners

  • 2021-11-01 23:44:54
  • OfStack

join () method: Joins all elements in an array into a string with a specified delimiter

Examples:


myArr.join('-') //  Use '-' Symbolic stitching 

concat () Method: Combine two or more arrays into one array

Examples:


myArr.concat(arr1, arr2, ..., arrN)

Note: This method does not change existing arrays, so it can be combined with empty arrays and duplicate old arrays without contaminating old array data when manipulating new array data

sort () method: Used to sort the elements of an array

If the method is called without parameters, the elements in the array are sorted alphabetically or, more precisely, in the order in which the characters are encoded. To achieve this point, you should first convert all the elements of the array into strings (if necessary) for comparison

Examples:


myArr.sort() //  In alphabetical order 
myArr.sort(function(a, b) {
	return a - b
}) //  In ascending order of numbers, descending order is b - a
//  Arrow function writing 
myArr.sort((a, b) => a - b)

reverse () method: Used to reverse the order of elements in an array

Examples:


myArr.reverse()

push ()/unshift () Method: Adds one or more elements to the end/beginning of an array and returns the new length

Examples:


myArr.push(item1, item2, ..., itemN)
myArr.unshift(item1, item2, ..., itemN)

shift () method: Deletes the first element of the array and returns the value of the first element

Examples:


myArr.shift()

pop () method: Deletes one element of the array (the last element by default) and returns the value of that element

Examples:


myArr.pop() //  Delete the last of the array 1 Elements 
myArr.pop(1) //  Delete the index in the array as 1 Elements of 

splice () method: Add/delete items to/from the array, and then return the deleted items


myArr.splice(index, count, item1, item2, ..., itemN)
// index  Necessary. Integer, specified to add / Delete the position of the item, and use a negative number to specify the position from the end of the array 
// count  Necessary. The number of items to delete. If set to  0 The item is not deleted 
// item1, item2, ..., itemN  Optional. A new item added to the array 

forEach () method: The method is used to call each element of the array and pass the element to the callback function (equivalent to an for loop)

Examples:


myArr.forEach(function (item, index, arr) {
 if (index === 3) {
 item = 123
 } 
}) //  Loop array with an index of 3 Change the element value of to 123
//  Arrow function writing 
myArr.forEach((v, i, arr) => if (i === 3) { v = 123 })

Note: None of the following methods will detect empty arrays and will not change the original array

indexOf () method: Finds if an element exists in the array, returns a subscript, or-1 if not

Examples:


myArr.indexOf(item)

Note: The indexOf () method is case sensitive!

slice () method: You can extract a part of a string and return the extracted part (elements of a shallow copy array) as a new string

Examples:


myArr.concat(arr1, arr2, ..., arrN)
0

every () method: Used to detect whether the elements in the array meet the specified conditions (provided by the function) (such as whether a value is all true)

If one element is not satisfied, the whole expression returns false and the detection stops; If all elements meet the conditions, true is returned

Examples:


const state = myArr.every(function (item, index, arr) {
 return item > 10
}) //  Detection array myArr Are all elements of the 10 , return 1 Boolean values state
//  Arrow function writing 
const state = myArr.every((v, i, arr) => v > 10)

some () method: Used to detect whether the elements in the array meet the specified conditions (provided by the function) (such as whether a value is true)

If one element is satisfied, the whole expression returns true and stops detection; If there are no elements that meet the conditions, false is returned

Examples:


const state = myArr.some(function (item, index, arr) {
 return item > 10
}) //  Detection array myArr Is there an element in the 10 , return 1 Boolean values state
//  Arrow function writing 
const state = myArr.some((v, i, arr) => v > 10)

includes () method: Used to determine whether the array contains the specified value. If a matching value is found, true is returned, otherwise false is returned

Note: The includes () method is case sensitive

Parameters:
searchvalue: Required, value to find

start: Optional, set the location from which to look, default to 0

Examples:


myArr.concat(arr1, arr2, ..., arrN)
3

filter () Method: Creates a new array of elements by checking all eligible elements in the specified array

Examples:


myArr.concat(arr1, arr2, ..., arrN)
4

map () method: Returns a new array with elements that are processed by the original array element call function

The map () method processes the elements in order of the original array elements

Examples:


myArr.concat(arr1, arr2, ..., arrN)
5

Example (type for array nested objects):


myArr.concat(arr1, arr2, ..., arrN)
6

find ()/findIndex () method: Returns the value/index of the first element of the array that passed the test (judged within the function). Returns undefined/-1 if there are no eligible elements

Examples:


const val = myArr.find(function (item, index, arr) {
 return item > 10
}) //  Return Array myArr Middle grade 1 Is greater than 10 The value of the element of val If there is no, return undefined

const val = myArr.findIndex(function (item, index, arr) {
 return item > 10
}) //  Return Array myArr Middle grade 1 Is greater than 10 If not, return the element index of -1

reduce () method: Returns a new array with elements that are processed by the original array element call function

This method takes two arguments: the function to execute and the initial value passed to the function

Functions to execute (total, currentValue, currentValue, arr):

total: Required, initial value, or return value after calculation

currentValue: Required, current element;

currentValue: Optional, current element index;

arr: Optional, the array object to which the current element belongs

Example 1:


const myArr = [1, 2, 3]
const sum = myArr.reduce(function(pre, cur, index, arr) {
 console.log(pre, cur)
 return pre + cur
})
console.log(sum)
//  The output values are 
// 1, 2
// 3, 3
// 6

Example 2 (setting the initial iteration value):


myArr.concat(arr1, arr2, ..., arrN)
9

Application:

1. Summing, multiplying


const myArr = [1, 2, 3, 4]
const result1 = myArr.reduce(function(pre, cur) {
 return pre + cur
})
const result2 = myArr.reduce(function(pre, cur) {
 return pre * cur
})
console.log(result1) // 6
console.log(result2) // 24

2. Count the number of occurrences of each element in the array


const myArr = ['liang','qi','qi','liang','ge','liang'] 
const arrResult = myArr.reduce((pre,cur) =>{
 if(cur in pre){
  pre[cur]++
 }else{
  pre[cur] = 1
 }
 return pre
},{})
console.log(arrResult) //  Results: {liang: 3, qi: 2, ge: 1}

3. Summing the properties of the object


const myArr = [
 {
  name: 'liangqi',
  weigth: 55
 },{
  name: 'mingming',
  weigth: 66
 },{
  name: 'lele',
  weigth: 77
 }
]
const result = myArr.reduce((a,b) =>{
 a = a + b.weigth
 return a
},0)
console.log(result) //  Results: 198

Array. of () Method: Used to convert 1 set of values to a new array

Examples:


Array.of() // []
Array.of(undefined) // [undefined]
Array.of(1) // [1]
Array.of(1, 2) // [1, 2]

flat () method: Array flattening method is also called array flattening, array flattening, array dimensionality reduction, which is used to change nested arrays into 1-dimensional arrays and return a new array

Examples:


const myArr = [1, [2, 3, [4, 5, [12, 3, "zs"], 7, [8, 9, [10, 11, [1, 2, [3, 4]]]]]]]
console.log(myArr.flat(Infinity)) // [1, 2, 3, 4, 5, 12, 3, "zs", 7, 8, 9, 10, 11, 1, 2, 3, 4]

Summarize


Related articles: