You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
这样会不会更好
const arr = [1, [1,2], [1,2,3]]
function flat(arr) {
let result = []
for (const item of arr) {
item instanceof Array ? result = result.concat(flat(item)) : result.push(item)
}
return result
}
Activity
352800205 commentedon Apr 3, 2020
补充:flat() 方法对node版本有要求,至少需要12.0以上,不知道的小伙伴会搞错,然后我的方法是
通过array.some() + concat来实现这个flat(),这个对node版本的限制比较低,可行性较高。。
源码:
ai977313677 commentedon Apr 6, 2020
给个递归方法:
ans是作为全局变量的,也可以作为参数传递。
这题的难点在于拍平数组,之后的去重可以用set,也可以用map,甚至可以用数组,排序可以自己写或者sort。
lyllovelemon commentedon Apr 8, 2020
diveDylan commentedon Apr 22, 2020
Aiyoweioo commentedon Apr 26, 2020
考虑到这儿有三个步骤,可以用函数组合compose来把这三个函数组合在一起。
参考数组去重:mqyqingfeng/Blog#27
参考redux的函数组合: https://github.com/reduxjs/redux/blob/master/src/compose.ts
sfsoul commentedon Apr 27, 2020
This looks so cool!But,it has a mistake。
const getArray = (arr, dep) => Array.from(new Set(arr.flat(dep))).sort((a,b) => a-b);zero9527 commentedon Apr 28, 2020
diveDylan commentedon Apr 28, 2020
it works well for me .
sfsoul commentedon Apr 28, 2020
plane-hjh commentedon Apr 28, 2020
直接为sort()是根据Unicode来排序的
Yin-fujun commentedon May 14, 2020
let array = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10]
// 转成字符串
let flatArr = array.toString(); //输出 "1,2,2,3,4,5,5,6,7,8,9,11,12,12,13,14,10"
// 去重、转成数组
let disArr = Array.from(new Set(flatArr.split(',')))
//排序
let result = disArr.sort((a,b) => a-b);
console.log(result)
// 输出 ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"]
zhangkaivictor commentedon Jun 17, 2020
var arr = [[1,2,2],[3,4,5,5],[6,7,8,9,[11,12,[12,13,[14]]]],10]
function flat (arr){
while(arr.some(it => Array.isArray(it))){
arr = [].concat(...arr)
}
arr = [...new Set(arr)].sort((a,b) => a - b)
return arr
}
console.log(flat(arr))
zhangkaivictor commentedon Jun 17, 2020
xblj commentedon Jul 9, 2020
Been101 commentedon Jul 11, 2020
hejunjieGitHub commentedon Jul 30, 2020
qianlongo commentedon Aug 15, 2020
njueyupeng commentedon Aug 17, 2020
yucheng-yc commentedon Nov 18, 2020
var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10]; // 将数组使用toString() 将数组进行扁平化(字符串) // 将扁平化的字符串变成 字符串数组 然后将字符串数组内的数据进行所有的转变 最后进行排序 var arrStr = arr.toString().split(',').map(Number).sort((a,b)=>a-b) console.log('arrStr',arrStr)huohuoit commentedon Apr 19, 2021
这样会不会更好
const arr = [1, [1,2], [1,2,3]]
function flat(arr) {
let result = []
for (const item of arr) {
item instanceof Array ? result = result.concat(flat(item)) : result.push(item)
}
return result
}
flat(arr) // [1, 1, 2, 1, 2, 3]
Baymaxxx commentedon May 30, 2021
sionnigjt commentedon Oct 23, 2021
xiaochengzi6 commentedon May 14, 2022
回字的四种写法
lyllovelemon commentedon May 14, 2022