xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

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

  1. 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]

  1. 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, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2020-04-18 22:30  xgqfrms  阅读(218)  评论(1编辑  收藏  举报