Array flattening
table of Contents
Array flattening refers to turning a multi-dimensional array into a one-dimensional array
[1, [2, 3, [4, 5]]] ------> [1, 2, 3, 4, 5]
achieve
1. reduce
- Traverse each item of the array, if the value is an array, traverse recursively, otherwise
concat
.
function flatten(arr) {
return arr.reduce((result, item)=> {
return result.concat(Array.isArray(item) ? flatten(item) : item);
}, []);
}
-
reduce
It is a method of an array. It receives a function as an accumulator. Each value in the array (from left to right) is reduced and finally calculated as a value. -
reduce
Contains two parameters: callback function, the initial value passed to total
// 求数组的各项值相加的和:
arr.reduce((total, item)=> {
// total为之前的计算结果,item为数组的各项值
return total + item;
}, 0);
2. toString & split
Call the array toString
method, turn the array into a string and then use the split
split to restore it to an array
function flatten(arr) {
return arr.toString().split(',').map(function(item) {
return Number(item);
})
}
Because split
each item of the array formed after the division is a string, it is necessary to use a map
method to traverse the array and convert each item to a numeric value.
3. join & split
Like the above toString
, join
you can also convert the array to a string
function flatten(arr) {
return arr.join(',').split(',').map(function(item) {
return parseInt(item);
})
}
4. Recursion
Recursively traverse each item, if it is an array, continue to traverse, otherwiseconcat
function flatten(arr) {
var res = [];
arr.map(item => {
if(Array.isArray(item)) {
res = res.concat(flatten(item));
} else {
res.push(item);
}
});
return res;
}
5. Spread operator
es6
The spread operator of can turn a two-dimensional array into a one-dimensional
[].concat(...[1, 2, 3, [4, 5]]); // [1, 2, 3, 4, 5]
According to this result, we can do a traversal. If arr contains an array, use the spread operator once until there is no array.
function flatten(arr) {
while(arr.some(item=>Array.isArray(item))) {
arr = [].concat(...arr);
}
return arr;
}
to sum up
Although five methods have been written, there is only one core:
Traverse the array arr, if arr[i] is an array, then recursively traverse until arr[i] is not an array and then the previous result is the same concat
.