Flattening arrays using javascript-5 methods
use recursion: map, reduce
function flatten(arr) {
var res = [];
arr.map(item => {
res = Array.isArray(item) ? res.concat(flatten(item)) : res.push(item);
});
return res;
}
function flatten(arr) {
return arr.reduce((result, item)=> {
return result.concat(Array.isArray(item) ? flatten(item) : item);
}, []);
}
loop, peel off layer by layer
function flatten(arr) {
while(arr.some(item=>Array.isArray(item))) {
arr = [].concat(...arr);
}
return arr;
}
cool techs: join, toString
function flatten(arr) {
return arr.join(",").split(",").map(function(item) {
return parseInt(item);
})
}
function flatten(arr) {
return arr.toString().split(",").map(function(item) {
return Number(item);
})
}
The two code blocks above
indicate that I can"t understand them either. Can you help me explain them?
1
join
is used to say that array elements are concatenated into a string according to a character. All elements of the
array are converted to the string
type. This is equivalent to calling all item
toString
and finally performing split
, dividing the string according to a certain character to get an array.
2
2 can be thought of as part of the 1 implementation
toString
, that is, convert the entire array to a string for output, and all item
will be converted to a string, which can be simply understood as a recursive process.
finally split
P.S. It's just a rough idea, and it doesn't guarantee that the process defined in the ECMAScript document is like this
.
official explanation: join () puts all the elements of the array into a string. Elements are separated by the specified delimiter, which defaults to','
let arr = [1,2,3,[34,12],[12,[34,[56,78]]]];
arr.join()
// "1,2,3,34,12,12,34,56,78"
arr.join(',')
// "1,2,3,34,12,12,34,56,78"
arr.toString()
// "1,2,3,34,12,12,34,56,78"
//split
arr.join(',').split(',')
// ["1", "2", "3", "34", "12", "12", "34", "56", "78"]
for this kind of thing that you don't understand, first break the point to see the result, and then look at the explanation. Most of the time, the explanation is not thorough and everyone's understanding is different. The key point is to know what the result will be and how to get it
simplify a little more:
function flatten(arr) {
return arr.join(',').split(',').map(Number);
}