gpt4 book ai didi

javascript - 使用reduce从数组中删除重复项

转载 作者:行者123 更新时间:2023-12-03 09:46:00 25 4
gpt4 key购买 nike

我正在尝试从数组列表中删除重复项。我尝试这样做的方法是使用 reduce 创建一个空数组,将所有 undefined index 推送到该数组上。虽然我收到了错误

if(acc[item]===undefined){
^
TypeError: Cannot read property '1' of undefined

我的功能如下:

function noDuplicates(arrays) {
var arrayed = Array.prototype.slice.call(arguments);

return reduce(arrayed, function(acc, cur) {
forEach(cur, function(item) {
if (acc[item] === undefined) {
acc.push(item);
}
return acc;
});
}, []);
}

console.log(noDuplicates([1, 2, 2, 4], [1, 1, 4, 5, 6]));

最佳答案

首先连接两个数组,接下来使用filter()只过滤掉唯一的项目-

var a = [1, 2, 2, 4], b = [1, 1, 4, 5, 6];
var c = a.concat(b);
var d = c.filter(function (item, pos) {return c.indexOf(item) == pos});
console.log(d);

关于javascript - 使用reduce从数组中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43773999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com