JS實作陣列扁平化處理
點擊打開視頻講解更加詳細
期望結果:
將陣列扁平化并去重
最終得到一個升序且不重復的陣列
步驟:
1、陣列扁平化
2、去重
3、排序
<template>
<div id="home">
JS實作陣列扁平化處理,妙不可言啊!
<!-- 期望結果:
將陣列扁平化并去重
最終得到一個升序且不重復的陣列
步驟:
1、陣列扁平化
2、去重
3、排序 -->
</div>
</template>
<script>
export default {
name: "home",
data() {
return {
arr: [
[1, 2, 3],
[3, 4, 5, 5],
[6, 7, 8, 9],
[11, 12, [12, 12, [13]]],
10,
],
};
},
mounted() {
// 方法 1
// let list = this.flat(this.arr);
// console.log(list);
// 方法 2
let list2 = this.flat2(this.arr);
console.log(list2);
},
components: {},
methods: {
//1、方法1 使用遞回;陣列扁平化處理
flat(arr) {
let result = arr.map((item) => {
if (Array.isArray(item)) {
return this.flat(item);
}
return [item];
});
return this.removal([].concat(...result));
},
//方法2 使用while回圈;處理陣列扁平化
flat2(arr) {
while (arr.some((item) => Array.isArray(item))) {
arr = [].concat(...arr);
}
return this.removal(arr);
},
// 2、去重
removal(arr) {
// return Array.from(new Set(arr));
return this.sort(Array.from(new Set(arr)));
},
//3、排序
/**
* 正數 a > b 降序(倒序)
* 0 a = b
* 負數 a < b 升序
*/
sort(arr) {
return arr.sort((a, b) => a - b);
},
},
};
</script>
<style scoped>
</style>
效果圖:

若對您有幫助,請點擊跳轉到B站一鍵三連哦!感謝支持!!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/505526.html
標籤:JavaScript
下一篇:promise
