Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Array flattening concept
Array flattening is the process of turning a multidimensional array into a one-dimensional array
[1[2.3[4.5]]] -- -- -- -- -- - > [1.2.3.4.5]
Copy the code
implementation
1. reduce
Iterate over each item of the group, recursively if the value is array, otherwise concat.
function flatten(arr) {
return arr.reduce((result, item) = > {
return result.concat(Array.isArray(item) ? flatten(item) : item); } []); }Copy the code
Reduce is a method of arrays that accepts a function as an accumulator, where each value in the array (from left to right) starts to shrink and eventually evaluates to a value. Reduce takes two parameters: a callback function and an initial value passed to total
// Find the sum of the values of the array:
arr.reduce((total, item) = > { // total is the result of the previous calculation, and item is the value of the array
return total + item;
}, 0);
Copy the code
2. toString & split
Call the toString method of the array, turn the array into a string and then split it back into an array
function flatten(arr) {
return arr.toString().split(', ').map(function(item) {
return Number(item); })}Copy the code
Because each item in a split array is a string, you need to use a map method to traverse the array to convert each item to a numeric value
3. join & split
Like toString above, a Join can convert an array to a string
function flatten(arr) {
return arr.join(', ').split(', ').map(function(item) {
return parseInt(item); })}Copy the code
4. The recursion
Each item is iterated recursively, continuing if it is an array, concat otherwise
function flatten(arr) {
var res = [];
arr.map(item= > {
if(Array.isArray(item)) {
res = res.concat(flatten(item));
} else{ res.push(item); }});return res;
}
Copy the code
5. Extend operators
Es6’s extension operator turns a two-dimensional array into a one-dimensional one
[].concat(... [1.2.3[4.5]]); // [1, 2, 3, 4, 5]
Copy the code
Based on this result we can do a traversal, using the extension operator once if the ARR contains an array, until there is none left.
function flatten(arr) {
while(arr.some(item= >Array.isArray(item))) { arr = [].concat(... arr); }return arr;
}
Copy the code
conclusion
Although there are five methods written, there is only one core: iterate over the array arr, recursively iterate if arr[I] is an array until arr[I] is not an array and concat the previous result.