題目:數組
已知以下數組:
var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];
編寫一個程序將數組扁平化去併除其中重複部分數據,最終獲得一個升序且不重複的數組
實現:this
var arr = [[1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10]; //數組扁平化 Array.prototype.flat = function() { return [].concat(...this.map(item => (Array.isArray(item) ? item.flat() : [item]))); } //去重 Array.prototype.unique = function() { return [...new Set(this)] } //排序 const sort = (a, b) => a - b; console.log(arr.flat().unique().sort(sort));
解析:prototype
數組扁平化,判斷數組子元素是否爲數組,是的話進行遞歸,不然把子元素變爲數組code
this.map(item => (Array.isArray(item) ? item.flat() : [item]))的執行結果爲排序
[[[1], [2], [2]], [[3], [4], [5], [5]], [[6], [7], [8], [9], [[11], [12], [[12], [13], [[14]]]]], [10]]
[].concat(...this.map(item => (Array.isArray(item) ? item.flat() : [item])))的執行結果爲遞歸
- [].concat([1], [2], [2]) -> [1, 2, 2]
- [].concat([3], [4], [5], [5]) -> [3, 4, 5, 5]
- [].concat([].concat([6], [7], [8], [9], [].concat([11], [12], [].concat([12], [13], [].concat([14]))))) -> [6, 7, 8, 9, 11, 12, 12, 13, 14]
- [].concat([10]) -> [10]
- [].concat([1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, 11, 12, 12, 13, 14], [10]) -> [1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12, 13, 14, 10]
數組去重, 經過Set實現it
- new Set(this) -> {1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 10}
- [...new Set(this)] -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 10]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]