平面化-排序-去重 一道面試題引起的思考

一道面試題引起的思考

參考資料html

數組去重方法面試

www.cnblogs.com/baiyangyuan…數組

[TOC]bash

面試題

// 輸入數據
const input =  [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10]

// 輸出數據
expect =  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 

// 附加條件 最好不要超過五行
複製代碼

學霸答案

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))

複製代碼
  • flat(Infinity) 不知道怎麼辦??

基礎知識

數組平面化

  • 循環+遞歸 (5行)
const flatten = input => {
    result = []
    input.forEach(v => Array.isArray(v) ? result = result.concat(flatten(v)) : result.push(v))
    return result
}
複製代碼
  • 歸併方法:reduceui

    (1行 不過太難於理解了)spa

    reduce的第二個參數:做爲歸併基礎的初始值code

    const flatten = input => input.reduce((prev, next) => prev.concat(Array.isArray(next) ? flatten(next) : next), []);
    複製代碼
  • ES6:...擴展運算符htm

    5行代碼對象

const flatten = input => {
    while(input.some(v => Array.isArray(v))){
        input = [].concat(...input)
    }
    return input
}
複製代碼
  • toString法blog

    一行代碼

    只適用於數組元素所有爲數字的狀況下

const flatten = ary => ary.toString().split(",").map(v => +v)
複製代碼

數組去重

  • 通常方法
const uniq = input => input.reduce((cur, next) => cur.indexOf(next) !== -1 ? cur : [...cur, next], [])
複製代碼
  • 對象鍵值 + reduce 去重

    速度最快, 佔空間最多(空間換時間)

    該方法執行的速度比其餘任何方法都快, 就是佔用的內存大一些。
    現思路:新建一js對象以及新數組,遍歷傳入數組時,判斷值是否爲js對象的鍵,
    不是的話給對象新增該鍵並放入新數組。
    注意點:判斷是否爲js對象鍵時,會自動對傳入的鍵執行「toString()」,
    不一樣的鍵可能會被誤認爲同樣,例如n[val]-- n[1]、n["1"];
    解決上述問題仍是得調用「indexOf」。*/
    複製代碼
    const obj = {}
    const uniq = input => input.reduce((cur, next) => obj[next] ? cur : obj[next] = true && [...cur, next], [])
    複製代碼
  • 排序相鄰去重

    一行搞定排序 + 去重

    const uniq = input => input.sort((a, b) => a > b).reduce((cur, next) => cur[cur.length - 1] === next ? cur : [...cur, next], [])
    複製代碼
  • 數組下標法

    const uniq = input => input.reduce((cur, next, i) => input.indexOf(next) !== i ? cur : [...cur, next], [])
    
    複製代碼
  • Set去重

    const uniq = input => [... new Set(input)]
    複製代碼
相關文章
相關標籤/搜索