如何用reduce和map获取多对象中vals数组的并集?
获取props中所有vals数组的并集
现有如下结构的props对象:
const props = { S1: { vals: [1, 2, 3, 4], /* 其他属性 */ }, S2: { vals: [3, 4, 5, 6], /* 其他属性 */ } };
需要得到所有vals数组的并集结果:
const res = [1, 2, 3, 4, 5, 6];
原尝试的代码写法有误:
const res = Object.entries(props).reduce((res, o) => res.union(Object.entries([k, v]) => v[vals]);
正确实现方式
可以结合Object.values(或Object.entries)、reduce和Set来实现——Set天然具备去重能力,刚好满足并集需求:
方法1:使用Object.values + reduce
const res = Array.from( Object.values(props).reduce((acc, item) => { // 将当前item的vals数组元素逐个加入Set自动去重 item.vals.forEach(num => acc.add(num)); return acc; }, new Set()) );
方法2:结合map和reduce
如果一定要用到map,可以先提取所有vals数组,再用reduce合并去重:
const res = Array.from( Object.values(props) .map(item => item.vals) // 提取所有vals数组,得到[[1,2,3,4], [3,4,5,6]] .reduce((acc, arr) => { arr.forEach(num => acc.add(num)); return acc; }, new Set()) );
若坚持使用Object.entries的写法
const res = Array.from( Object.entries(props).reduce((acc, [key, item]) => { item.vals.forEach(num => acc.add(num)); return acc; }, new Set()) );
关键说明
- 原生数组没有
union方法,原代码中res.union的写法是错误的,这是代码失效的核心原因之一。 Set会自动过滤重复元素,最后通过Array.from将Set转换为普通数组,得到最终的并集结果。
内容的提问来源于stack exchange,提问作者Osman Mamun
相关产品推荐
相关产品推荐

