We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
数据扁平化是指将多维的数组压成一维的数组,不存在数组嵌套的问题。数组扁平化的一些常用方法如下:
flat(depth) 方法中的参数depth,代表展开嵌套数组的深度,默认是1。如果我们想把任意维数组扁平为1维数组,可以使用arr.flat(dimension-1)或arr.flat(Infinity)操作。
arr.flat(dimension-1)
arr.flat(Infinity)
let a = [1,[2,3,[4,[5]]]]; console.log(a.flat()) console.log(a.flat(1)) console.log(a.flat(4-1)) console.log(a.flat(Infinity)) // [ 1, 2, 3, [ 4, [ 5 ] ] ] // [ 1, 2, 3, [ 4, [ 5 ] ] ] // [ 1, 2, 3, 4, 5 ] // [ 1, 2, 3, 4, 5 ]
var arr1 = [1, 2, 3, [1, 2, 3, 4, [2, 3, 4]]]; const flatten = arr => { var res = []; for (let i = 0, length = arr.length; i < length; i++) { if (Array.isArray(arr[i])) { res = res.concat(flatten(arr[i])); //concat 并不会改变原数组 //res.push(...flatten(arr[i])); //扩展运算符 } else { res.push(arr[i]); } } return res; } console.log(flatten(arr1)); //[1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
var arr1 = [1, 2, [3], [1, 2, 3, [4, [2, 3, 4]]]]; const flatten = arr => { // 只有arr中有元素为数组,则展开此元素 // 再判断arr中是否有元素为数组,有则再展开…… // 循环往复,直到arr中再也没有数组 while (arr.some(item => Array.isArray(item))) { arr = [].concat(...arr); //arr = Array.prototype.concat.apply([],arr); } return arr; } console.log(flatten(arr1)); //[1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
var arr1 = [1, 2, [3], [1, 2, 3, [4, [2, 3, 4]]]]; const flatten = arr => { return arr.reduce((pre, cur) => { return pre.concat(Array.isArray(cur) ? flatten(cur) : cur); }, []); } console.log(flatten(arr1)); //[1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
function flatten(input) { return input.toString().split(',').map(item => +item); // return input.join().split(',').map(item => +item); // return input.join(',').split(',').map(item => +item); } console.log(flatten(arr1)); //[1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
The text was updated successfully, but these errors were encountered:
No branches or pull requests
数据扁平化是指将多维的数组压成一维的数组,不存在数组嵌套的问题。数组扁平化的一些常用方法如下:
方法1:使用flat函数
flat(depth) 方法中的参数depth,代表展开嵌套数组的深度,默认是1。如果我们想把任意维数组扁平为1维数组,可以使用
arr.flat(dimension-1)
或arr.flat(Infinity)
操作。方法2:使用for循环
方法3:使用while循环
方法4:使用reduce
方法5:转化为字符串
The text was updated successfully, but these errors were encountered: