Deduplication
Using Set properties
[JavaScript] plain text view Copy the code
1
|
const arr = [1, 2, 2, 3, 4, 7, 7]const uniqueArr = [... new Set(arr)]console.log(uniqueArr) // [1, 2, 3, 4, 7]某一个位置插入元素
|
Change the original array
[JavaScript] plain text view Copy the code
1
|
const arr = [1, 2, 3, 5, 6, 7]arr.splice(3, 0, 4)console.log(arr) // [1, 2, 3, 4, 5, 6, 7]
|
It does not change the original array
[JavaScript] plain text view Copy the code
1
|
const arr = [1, 2, 4, 5]const indexNeededToInsert = 2const newArr = [...arr.slice(0, indexNeededToInsert), 3, ...arr.slice(indexNeededToInsert)]console.log(newArr) // [1, 2, 3, 4, 5]console.log(arr)// [1, 2, 4, 5]删除某一个位置的元素
|
It does not change the original array
const arr = [1, 2, 3, 4, 5]const indexToBeRemoved = 3const filteredArr = arr.filter((_, index) => index !== indexToBeRemoved)console.log(filteredArr)// [1, 2, 3, 5]console.log(arr)// [1, 2, 3, 4, 5]
Change the original array
[JavaScript] plain text view Copy the code
1
|
const arr = [1, 2, 3, 4, 5]const indexToBeRemoved = 3arr.splice(indexToBeRemoved, 1)console.log(arr) // [1, 2, 3, 5]获取数组最后一个元素
|
Change the original array
[JavaScript] plain text view Copy the code
1
|
const arr = [1, 2, 3, 4, 5]const lastElement = arr.pop()console.log(lastElement) // 5console.log(arr)// [1, 2, 3, 4]
|
It does not change the original array
[JavaScript] plain text view Copy the code
1
|
const arr = [1, 2, 3, 4, 5]const lastElement = arr.slice(-1)[0]console.log(lastElement) // 5console.log(arr)// [1, 2, 3, 4, 5]
|
slice If the first argument is negative from the back showing several elements counted from the start of the second, -1 represents the inverse of the first element.
Empty Array
[JavaScript] plain text view Copy the code
1
|
const arr = [1, 2, 3, 4, 5]arr.length = 0console.log(arr) // []console.log(arr[0])// undefined
|
Generating an array of a length of
[JavaScript] plain text view Copy the code
1
|
const newArr = new Array(10)console.log(newArr) // [ <10 empty items> ]
|
The intersection of two arrays
[JavaScript] plain text view Copy the code
1
|
const arr1 = [1, 2, 3, 4]const arr2 = [2, 3]const intersectedArr = arr1.filter(item1 => arr2.includes(item1))console.log(intersectedArr) // [2, 3]
|
Merge multiple arrays
[JavaScript] plain text view Copy the code
1
|
const arr1 = [1, 2, 3]const arr2 = [4, 5, 6]const arr3 = [7, 8, 9]const mergedArr = [...arr1, ...arr2, ...arr3]console.log(mergedArr) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
|
Removing an array of false (falsy) value
[JavaScript] plain text view Copy the code
1
|
const mixedArr = [0, “blue”, “”, NaN, 9, true , undefined, “white”, false ]const trueArr = mixedArr.filter(Boolean);console.log(trueArr) // [“blue”, 9, true, “white”]
|
Summing
[JavaScript] plain text view Copy the code
1
|
const nums = [1, 2, 3, 4, 5]const sum = nums.reduce((currSum, num) => currSum + num)console.log(sum) // 15
|