封裝排序方法,asc:升序 desc:降序
let lessons = [{ a: 1, b: 2, c: 3 }, { a: 2, b: 3, c: 4 }, { a: 3, b: 4, c: 5 }, { a: 4, b: 5, c: 6 }] function order(field, type = "asc") { return function (a, b) { if (type == 'asc') return a[field] > b[field] ? 1 : -1; return a[field] > b[field] ? -1 : 1; } } let hd = lessons.sort(order('a', 'desc'))
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
flat方法
Array.prototype.flat()用於將嵌套的數組“拉平”,變成一維數組。該方法返回一個新數組,對原數據沒有影響。
[1, 2, [3, 4]].flat() // [1, 2, 3, 4]
- 1
- 2
flat()默認只會“拉平”一層,如果想要“拉平”多層的嵌套數組,可以將flat()方法的參數寫成一個整數,表示想要拉平的層數,默認為1。
[1, 2, [3, [4, 5]]].flat() // [1, 2, 3, [4, 5]] [1, 2, [3, [4, 5]]].flat(2) // [1, 2, 3, 4, 5]
- 1
- 2
- 3
- 4
如果不管有多少層嵌套,都要轉成一維數組,可以用Infinity關鍵字作為參數。
[1, [2, [3]]].flat(Infinity) // [1, 2, 3]
- 1
- 2
如果原數組有空位,flat()方法會跳過空位。
[1, 2, , 4, 5].flat() // [1, 2, 4, 5]
- 1
- 2
flatMap()方法對原數組的每個成員執行一個函數,相當於執行Array.prototype.map(),然后對返回值組成的數組執行flat()方法。該方法返回一個新數組,不改變原數組。
// 相當於 [[2, 4], [3, 6], [4, 8]].flat() [2, 3, 4].flatMap((x) => [x, x * 2]) // [2, 4, 3, 6, 4, 8]
轉載 https://blog.csdn.net/weixin_46845202/article/details/112259190