从数组中删除重复的值可以通过以下几种方法实现:
const array = [1, 2, 3, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // [1, 2, 3, 4, 5]
推荐的腾讯云相关产品:无
const array = [1, 2, 3, 3, 4, 4, 5];
const uniqueArray = array.filter((value, index, self) => {
return self.indexOf(value) === index;
});
console.log(uniqueArray); // [1, 2, 3, 4, 5]
推荐的腾讯云相关产品:无
const array = [1, 2, 3, 3, 4, 4, 5];
const uniqueArray = array.reduce((accumulator, currentValue) => {
if (!accumulator.includes(currentValue)) {
accumulator.push(currentValue);
}
return accumulator;
}, []);
console.log(uniqueArray); // [1, 2, 3, 4, 5]
推荐的腾讯云相关产品:无
当数组中的对象属性未定义时,可以使用以下代码来避免代码失败:
const array = [{ id: 1 }, { id: 2 }, { id: undefined }, { id: 3 }];
const uniqueArray = array.reduce((accumulator, currentValue) => {
const existingObject = accumulator.find(obj => obj.id === currentValue.id);
if (!existingObject) {
accumulator.push(currentValue);
}
return accumulator;
}, []);
console.log(uniqueArray); // [{ id: 1 }, { id: 2 }, { id: undefined }, { id: 3 }]
在这段代码中,我们使用 find 方法来查找数组中是否已存在具有相同 id 属性的对象,如果不存在则将当前对象添加到结果数组中。这样即使对象的属性未定义,代码也不会失败。
希望以上答案能够满足您的需求,如果有任何问题,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云