【问题标题】:how to make an array unique using reduce method of javascript如何使用javascript的reduce方法使数组唯一
【发布时间】:2022-01-22 19:45:00
【问题描述】:
我已经创建了一个示例供您理解问题。
let arr = [];
arr.push({
module_id: 41,
name: 'first'
}, {
module_id: 41,
name: 'second',
important: true,
}, {
module_id: 43,
name: 'third'
});
const lookup = arr.reduce((a, e) => {
a[e.module_id] = ++a[e.module_id] || 0;
return a;
}, {});
console.log('lookup is', lookup);
let unique = [];
arr.filter((e) => {
if (lookup[e.module_id] === 0) {
unique.push(e)
}
})
console.log('unique', unique)
首先,我有一个空数组arr,我在其中推入 3 个对象。
注意,module_name。有两个重复,我想使用属性名称为important 的第二个。
我在这里使用reduce 来找出基于module_name 重复的那个。它将返回 1 和 41 的键和 0 的 43。我想同时使用两者,但我不想复制到我的 unique 数组中。目前,我只会推送那些独特的元素,在我们的例子中是module_id: 43。
现在如何获取重复值(使用important 属性)?
【问题讨论】:
标签:
javascript
arrays
reactjs
object
【解决方案1】:
您可以使用 Map 并仅获取不同的第一个值或具有重要标志的值。
const
array = [{ module_id: 41, name: 'first' }, { module_id: 41, name: 'second', important: true }, { module_id: 43, name: 'third' }],
result = Array.from(array
.reduce(
(m, o) => m.set(o.module_id, !o.important && m.get(o.module_id) || o),
new Map
)
.values()
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
【解决方案2】:
试试
let unique = [];
arr.filter((e) => {
if (lookup[e.module_id] === 0) {
unique.push(e)
}
else if (e.important) {
unique.push(e)
}
})
【解决方案3】:
let arr = [];
arr.push(
{
module_id: 41,
name: 'first',
},
{
module_id: 41,
name: 'second',
important: true,
},
{
module_id: 43,
name: 'third',
}
);
const result = arr.reduce(
(acc, curr) =>
acc.find((v) => v.module_id === curr.module_id) ? acc : [...acc, curr],
[]
);
console.log(result);