Arrays are widely used data structures in JS. Array objects provide a number of useful methods to manipulate arrays, such as array.foreach (), array.map(), and so on. In practice, I’m often at a loss as to what arrays are possible to manipulate and which is better, so here’s a list of 15 common data methods to refresh my memory.
1. Array traversal
1.1 for... of
cycle
for… Of iterates through a set of items, such as a list of colors:
let color = ['red'.'orange'.'yellow'.'green'.'blue'];
for(let i of color){
console.log(i);
}
// 'red'
// 'orange'
// 'yellow'
// 'green'
// 'blue'
Copy the code
You can stop traversal with the break statement
1.2 for
cycle
for… In iterates through a number of items using an increasing index variable
let color = ['red'.'orange'.'yellow'.'green'.'blue'];
for(let i = 0; i < color.length; i++){
console.log(color[i]);
}
// 'red'
// 'orange'
// 'yellow'
// 'green'
// 'blue'
Copy the code
This method can also stop traversal with a break statement. Note the for loop and for… In loop, for… The in loop iterates through all enumerable attributes of a set, including stereotypes, so don’t use for.. This is also for… In and for… One of the differences between of.
1.3 Array.forEach()
cycle
The forEach loop loops through each array item by calling a callback function that takes the current item, the current item’s index, and the array being traversed:
let color = ['red'.'orange'.'yellow'];
color.forEach((item,index,arr) = >{
console.log(item, index);
});
// 'red' 0
// 'orange' 1
// 'yellow' 2
Copy the code
The forEach loop cannot be broken
2. Array mapping
2.1 Array.map()
methods
Array.map() generates a new Array by calling the result of the callback on each item of the Array. The callback takes the current item, the current item’s index, and the Array currently iterated over, multiplying the value of the Array by 2 as follows:
let arr = [2.4.5];
let arr2 = arr.map((item,value) = >{
return item *2;
});
/ / arr2 = >,8,10 [4]
Copy the code
Array.map () creates a new mapped array without changing the original array.
2.2 Array.from()
methods
The array.from () method creates a new Array by using the result of the callback call on each Array item.
let arr = [2.4.5];
let arr2 = Array.from(arr,(item)=>{
return item*2
});
/ / arr2 = >,8,10 [4]
Copy the code
1.Array.from() creates a new mapped Array without changing the original Array.
2.Array.from() is better for mapping from array-like objects
3. Array simplification
3.1 Array.reduce()
methods
Array.reduce() reduces the Array to a single value through the callback function, which in each iteration uses the arguments: accumulator, current item, index, and Array itself and should return an accumulator, such as a sum of numbers:
let arr = [2.4.5];
let sum = arr.reduce((accumulator, number) = >{
console.log(accumulator, number)
return accumulator + number
},0)
// sum => 11
Copy the code
4. Join arrays
4.1 array.concat()
methods
Concatenate one or more arrays to the original array as follows
let arr = ['jack'.'ace'];
let arr2 = ['taro'.'seven'];
let arr3 = arr.concat(arr2);
// arr3 => ['jack','ace','taro','seven']
Copy the code
Concat () creates a new array without changing the original array
Array. concat accepts multiple arrays to concatenate.
4.2 Expand operators
The expansion operator… To convert an array to a comma-separated sequence of arguments:
console.log(... [1.2.5.6]);
/ / 1,2,5,6
Copy the code
We can concatenate arrays with the expansion operator and array literals:
[[...13.5.7],... [65.174]]./ /,5,7,65,174 [13]
Copy the code
5. Get the array fragment
5.1 array. The slice () method
The array.slice method returns an array fragment, starting with fromIndex and ending with toIndex (excluding fromIndex, which defaults to 0, and toIndex, which defaults to Array.length.
let names = ['zoffy'.'seven'.'taro'];
let newNames = names.slice(1.2);
// newNames => ['seven']
Copy the code
Array.slice () creates a new array without altering the original array.
6. Copy the array
6.1 Expand operators
An easy way to copy an array is to use the expansion operator const clone = [… array], as shown below, to copy the colors array:
let colors = ['white'.'black'.'gray'];
let clone = [...colors];
clone; // => ['white', 'black', 'gray']
colors === clone; // => false
Copy the code
[…array] Creates a shallow copy.
6.2 array.concat()
methods
[].concat(array) is another way to copy arrays.
const colors = ['white'.'black'.'gray'];
const clone = [].concat(colors);
clone; // => ['white', 'black', 'gray']
colors === clone; // => false
Copy the code
[]. Concat (array) Creates a shallow copy.
6.3 array.slice()
methods
Array.slice () is another way to copy an array.
const colors = ['white'.'black'.'gray'];
const clone = colors.slice();
clone; // => ['white', 'black', 'gray']
colors === clone; // => false
Copy the code
Colors.slice () creates a shallow copy.
7. Find the array
7.1 array.includes()
methods
Array.includes () returns a Boolean value for whether array contains itemToSearch. The optional fromIndex parameter, which defaults to 0, indicates the index to start the search. Check whether 2 and 99 exist in a set of numbers:
const numbers = [1.2.3.4.5];
numbers.includes(2); // => true
numbers.includes(99); // => false
Copy the code
7.2 array.find()
methods
The array.find(predicate) method returns the value of the first element in the array that satisfies the provided test function. Otherwise return undefined. Find the first even number in the array as follows:
const numbers = [1.2.3.4.5];
function isEven(number) {
return number % 2= = =0;
}
const evenNumber = numbers.find(isEven);
evenNumber; / / = > 2
Copy the code
7.3 array.indexOf()
methods
Array.indexof () returns the indexOf the first itemToSearch to appear in an array. The optional fromIndex parameter, which defaults to 0, indicates the index to start the search.
const names = ["Little wisdom"."Little Brains at the front."."Wang"."Little three"]
const index = names.indexOf('Little Head')
index / / 1
Copy the code
If the item cannot be found, array.indexof (itemToSearch) returns -1
Array.findindex (predicate) is an alternative to using the predicate function to find indexes.
8. Query arrays
8.1 array.every()
methods
Return true if each item traversed passes the callback function; otherwise return false:
let list = [2.6.4.12];
let res = list.every((item) = >{
return item%2= = =0;
});
// res => true
Copy the code
8.2 array.some()
methods
Returns true if only one of each item passes the callback function check.
let list = [1.3.4.13];
let res = list.every((item) = >{
return item%2= = =0;
});
// res=> true;
Copy the code
9. Array filtering
9.1 array.filter()
methods
The array.filter method creates a new array containing all the elements of the test implemented through the provided function.
let list = [1.2.4.5.8.10];
let res = list.filter(item= >{
return item%2= = =0;
});
/ / res = >,4,8,10 [2]
Copy the code
10. Array insertion
10.1 array.push
methods
Adds one or more items to the end of an array and returns the length of the array:
let list = [1.2.3];
let len = list.push(4.5);
// len => 5
/ / the list = > [1, 2, 3, 4, 5]
Copy the code
This method changes the original array
10.2 array.unshift
methods
Add one or more items to the array header:
let list = [3.2.1];
let len = list.unshift(5.4);
// len => 5
// list =>
Copy the code
This method changes the original array;
The insertion sequence is from right to left, that is, 4 is inserted in the head first and 5 is inserted in the head
11. Delete array elements
11.1 array.pop
methods
Removes the last element from the array and returns the changed element:
let list = [1.2.3];
let res = list.pop();
/ / the list = > [1, 2]
// res => 3
Copy the code
This method changes the original array
11.2 array.shift
methods
Removes the first element from the array and returns it.
let list = [1.2.3];
let res = list.shift();
/ / the list = > [2, 3]
// res => 1
Copy the code
This method changes the original array
11.3 array.splice
methods
Delete an element from an array and add a new element:
let list = [1.2.3.4.5.6];
let res1 = list.splice(2.4);
// Delete four elements from index 2
/ / the list = > [1, 2]
/ / res1 = >,4,5,6 [3]
let res2 = list.splice(1.1.'8');
/ / the list = > [1]
Copy the code
This method changes the original array
12. Empty the array
12.1 array.length
attribute
Array. length is the property that holds the length of the array. In addition, array.length is writable. If I write an array.length = newLength less than the current length, the extra elements are removed from the array:
let list = [1.2.3];
list.length = 0
Copy the code
12.2 array.splice
methods
If the second argument is omitted, array.splice() removes all elements of the array starting at the index of the first argument. Let’s use it to delete all elements from the array:
let list = [1.2.3];
list.splice(0);
// list => []
Copy the code
13. Populate the array
13.1 array.fill
methods
The method accepts three parameters, namely, fill value, fill start position, and fill end position (excluding itself) :
let list = [1.2.3.4];
list.fill(0.0.2);
/ / the list = >,0,3,4 [0]
list.fill(5);
/ / the list = >,5,5,5 [5]
Copy the code
Array. fill changes the original array
13.2 Array.from
methods
let list = [1.2.3];
let res = Array.from(list,(item)=>{
return 0
});
/ / res = > [0, 0]
Copy the code
14. Flattening arrays
14.1 array.flat
methods
The array.flat([depth]) method creates a new array by recursively flattening the items that belong to the array to a certain depth. Depth The default value is 1.
let list = [1[2.3].4[5.6.7]].let res = list.flat();
/ / res = >,2,3,4,5,6,7 [1]
Copy the code
Array.flat () creates a new array without changing the original array.
15. Sort arrays
15.1 array.sort
methods
The array.sort([compare]) method sorts the elements of an array.
If compare is not specified, the element is sorted by the Unicode loci of the characters in the converted string.
The optional argument compare(a, b) is a custom collated callback function. Compare (a, b) :
- if
a
Less thanb
,a
Will be inb
In this case, you need to return a negative number; - if
a
Is greater thanb
,a
Will be inb
After, you need to return a positive number; - if
a
Is equal to theb
.a
和b
The relative position of is constant.
let list = [4.2.1.7.5];
list.sort((a,b) = >{
return a - b
})
/ / the list = >,2,4,5,7 [1]
Copy the code
Array.sort () changes the original array.
Reference links:
- Review 15 common array operations in JS by example (cheat list)
- MDN JavaScript standard built-in object
- ECMAScript 6 Introduction by Yifeng Ruan