js flat array All In One
js flat array All In One
flat array
使用 js 编写一个程序将
数组扁平化
并去除
其中重复
部分数据,最终得到一个升序
且不重复的数组;
已知如下数组:
const arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];
solutions
Array.flat
const arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];
// (4) [Array(3), Array(4), Array(5), 10]
// 数组扁平化
let newArr = arr.flat(Infinity);
// (17) [1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12, 13, 14, 10]
// 去重
newArr = [...new Set(newArr)];
// (14) [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 10]
// 排序, asc (ascend / 升序)
newArr.sort((a, b) => a - b > 0 ? 1 : -1);
// (14) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
- recursion
// 递归
const arrFlat = (arr = []) => {
let result = [];
arr.forEach((item, i) => {
if(Array.isArray(item)) {
const temp = arrFlat(item)
result = result.concat(temp);
} else {
result.push(item);
}
});
return result;
}
const arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];
// (4) [Array(3), Array(4), Array(5), 10]
let newArr = arrFlat(arr);
// (17) [1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12, 13, 14, 10]
newArr = [...new Set(newArr)];
// (14) [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 10]
newArr.sort((a, b) => a - b > 0 ? 1 : -1);
// (14) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
https://www.cnblogs.com/xgqfrms/p/10954098.html
https://www.cnblogs.com/xgqfrms/p/11349814.html
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/12728661.html
未经授权禁止转载,违者必究!