如何从多数组中生成无重复值的新数组?求快捷实现方法
合并多数组并去重的实现方案
嘿,这个需求完全不需要额外插件,用原生JavaScript就能轻松搞定!针对你给出的对象结构,我给你几种实用的实现方式:
方案一:ES6+ 极简写法(推荐)
利用Object.values()提取对象中的所有数组,结合flat()扁平化数组,再通过Set的特性自动去重,最后转回数组即可。如果需要有序的结果,再加个排序:
const x = { "12": [3, 4], "13": [3], "14": [1, 4] }; // 提取所有数组并扁平化 const merged = Object.values(x).flat(); // 去重+排序 const uniqueSorted = [...new Set(merged)].sort((a, b) => a - b); console.log(uniqueSorted); // 输出 [1, 3, 4]
方案二:兼容旧环境的手动遍历写法
如果你的项目需要兼容不支持ES6+的老环境,可以用手动遍历的方式:
const x = { "12": [3, 4], "13": [3], "14": [1, 4] }; const uniqueArray = []; // 遍历对象的每个属性对应的数组 for (const key in x) { if (Object.prototype.hasOwnProperty.call(x, key)) { x[key].forEach(item => { // 检查元素是否已存在,不存在则添加 if (!uniqueArray.includes(item)) { uniqueArray.push(item); } }); } } // 排序得到期望的顺序 uniqueArray.sort((a, b) => a - b); console.log(uniqueArray); // 输出 [1, 3, 4]
可选:用工具库简化(如Lodash)
如果你的项目已经引入了Lodash,可以直接用它的_.union方法,一行搞定:
const x = { "12": [3, 4], "13": [3], "14": [1, 4] }; const uniqueArray = _.union(...Object.values(x)).sort((a, b) => a - b); console.log(uniqueArray); // 输出 [1, 3, 4]
不过还是更推荐原生方案,毕竟没必要为这个小需求额外引入依赖~
内容的提问来源于stack exchange,提问作者Adam
相关产品推荐
相关产品推荐

