數組扁平化並去重排序

題目

var arr=[ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];git

1 .github

Array.from(new Set(arr.flat(Infinity))).sort((a,b)=>{ return a-b})

2 .數組

function flatten(arr) {
    while (arr.some(item => Array.isArray(item))) {
        arr = [].concat(...arr);
    }
    return arr;
}
Array.from(new Set(flatten(arr))).sort((a, b) => {
 return a - b
})

3.spa

Array.from(new Set(arr.toString().split(',').map((v)=>{return parseInt(v,10)}))).sort((a,b)=>{ return a-b})

相關知識

Set

[...new Set('ababbc')].join('')
// "abc"  去除字符串裏面的重複字符。
const set = new Set([1, 2, 3, 4, 4]);
[...set]
// [1, 2, 3, 4]

...

console.log(...[1, 2, 3])   //1 2 3
console.log([1, 2, 3])   // [1, 2, 3]

該運算符將一個數組,變爲參數序列。code

展平數組的方法

1.contact

只能展平一層blog

[1,2,3].concat([4,5,6],[7,8,9]) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
['a','b','c'].concat(1,[2,3],[[4,5]]) // ["a", "b", "c", 1, 2, 3, [4,5]]

clipboard.png

2. flat

[1, 2, [3, 4]].flat()
// [1, 2, 3, 4]
[1, 2, [3, [4, 5]]].flat()
// [1, 2, 3, [4, 5]]  默認爲1。

[1, 2, [3, [4, 5]]].flat(2)
// [1, 2, 3, 4, 5]
[1, [2, [3]]].flat(Infinity)
// [1, 2, 3] 
// 若是無論有多少層嵌套,都要轉成一維數組,能夠用`Infinity`關鍵字做爲參數。
[1, 2, , 4, 5].flat()
// [1, 2, 4, 5]   若是原數組有空位,`flat()`方法會跳過空位。

3.toString()

toString()展平後每一個數組中的至是字符串,可根據須要再轉換ip

var arr=[ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];
arr.toString();

clipboard.png

參考文章字符串

相關文章
相關標籤/搜索