Skip to content
New issue

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

数组扁平化、去重、排序 #28

Open
sisterAn opened this issue Feb 16, 2019 · 7 comments
Open

数组扁平化、去重、排序 #28

sisterAn opened this issue Feb 16, 2019 · 7 comments

Comments

@sisterAn
Copy link
Owner

sisterAn commented Feb 16, 2019

看一道面试题:

已知如下数组:var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];

编写一个程序将数组扁平化去并除其中重复部分数据,最终得到一个升序且不重复的数组

答案:

var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10]
// 扁平化
let flatArr = arr.flat(4)
// 去重
let disArr = Array.from(new Set(flatArr))
// 排序
let result = disArr.sort(function(a, b) {
    return a-b
})
console.log(result)
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

关于 Set 请查阅 Set、WeakSet、Map及WeakMap

@sunnyBob
Copy link

数组扁平化的处理,flat方法浏览器支持度很差,还是建议用递归的方式处理下

@caigehui
Copy link

@sunnyBob 如果涉及到浏览器,早在babel阶段就会对flat方法自动转化了

@sunnyBob
Copy link

sunnyBob commented Sep 19, 2019

image
babel 不会解决这种浏览器兼容问题

@caigehui
Copy link

caigehui commented Sep 19, 2019

@sunnyBob 你要引入@babel/polyfill啊,这个flat方法是polyfill实现的,怎么不会解决这种浏览器兼容问题?

@sunnyBob
Copy link

好的,查了下 core-js@3 增加了 flat 支持

@tim945
Copy link

tim945 commented May 19, 2020

var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10]
// 扁平化
let flatArr = arr.toString()

@qbright
Copy link

qbright commented Apr 13, 2021

我想到的也是用 toString去扁平化,不知道会不会有什么边界问题没办法处理

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants