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

排序面试题 #1

Open
su37josephxia opened this issue Mar 26, 2019 · 4 comments
Open

排序面试题 #1

su37josephxia opened this issue Mar 26, 2019 · 4 comments

Comments

@su37josephxia
Copy link
Owner

面试题,var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];转化为 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 请用不超过五行代码处理

@LeishenKOBE
Copy link

arr.flat(Infinity)

@wujiankun
Copy link

  var arrTarget = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];
       function arrFlatten(arr){
           let tempIdx=-1,tempItem=null;
           while (arr.some((item,idx)=>{
               tempIdx = idx; tempItem=item;return Array.isArray(item)
           })){
               arr.splice(tempIdx,1);
               arr = [...tempItem,...arr];
           }
           return Array.from(new Set(arr));
       }
       let result = arrFlatten(arrTarget).sort();

@su37josephxia
Copy link
Owner Author

su37josephxia commented Mar 26, 2019

最精简答案 只有一行

  • flat(Infinity) 扁平化
  • Set去重
    假设我不知道这两个函数如何解决
const ary = [[1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]]]], 10]
console.log('ary', [... new Set(ary.flat(Infinity))].sort((a, b) => a - b))

@AprilYUE
Copy link

AprilYUE commented Apr 2, 2019

var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];
let arr1=[]
let parse = function(arr){
Array.from(arr).forEach(a=>{
typeof a == 'object'?parse(a):(arr1.includes(a)?a:arr1.push(a))
})
}
parse(arr)
arr1=arr1.sort((a,b)=>(a-b))
console.log(arr1)

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

4 participants