js array merge, deduplication, dimensionality reduction
1. Merge
1.1 Use concat() to merge arrays
function get_concat(collection_a, collection_b) {
return collection_a.concat(collection_b)
}
1.2 Use ... (spread operator) to merge arrays
function get_concat(collection_a, collection_b) {
return [...collection_a,...collection_b]
}
2. Deduplication
2.1 use for
function get_union(array) {
let temp = []
for (let i = 0; i < array.length; i++) {
if (temp.indexOf(array[i]) == -1) {
temp.push(array[i])
}
}
return temp
}
2.2 Using spread operator, Set
function get_union(collection) {
return [...new Set(collection)]
}
The idea is array=> Set => array
- array=> Set
new Set(array) - The second step Set => array
[…Set]
ps: ES6 provides a new data structure Set. It is similar to an array, but the values of the members are all unique, and there are no duplicate values. A bit of the meaning of the heterogeneity
of sets in mathematics : in a set, any two elements are considered to be different, that is, each element can only appear once.
3. Dimensionality reduction
Reduce the 2-dimensional array to 1-dimensional, use flat()
function double_to_one(collection) {
return collection.flat();
}
3.1 flat() method
The flat() method will recursively traverse the array according to a specified depth, and combine all elements with the elements in the traversed sub-array to return a new array.
grammar
var newArray = arr.flat([depth])
The parameter
depth is optional
to specify the structure depth of the nested array to be extracted, and the default value is 1.
Return Value A new array
containing all the elements in the array and subarrays .