我试图从数组列表中删除重复项.我尝试这样做的方法是使用reduce创建一个空数组,将所有未定义的索引推送到该数组.我虽然得到了错误
if(acc[item]===undefined){
^
TypeError: Cannot read property '1' of undefined
Run Code Online (Sandbox Code Playgroud)
我的功能如下:
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]));Run Code Online (Sandbox Code Playgroud)
首先连接两个数组,然后使用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);Run Code Online (Sandbox Code Playgroud)
如何调用方法以及从何处返回acc存在许多问题:
function noDuplicates(arrays) {
var arrayed = Array.prototype.slice.call(arguments);
// reduce is a method of an array, so call it as a method
// return reduce(arrayed, function(acc, cur) {
return arrayed.reduce(function(acc, cur) {
// Same with forEach
cur.forEach(function(item) {
if (acc[item] === undefined) {
acc.push(item);
}
// Return acc from the reduce callback, forEach returns undefined always
// return acc;
});
return acc;
}, []);
}
console.log(noDuplicates([1, 2, 2, 4], [1, 1, 4, 5, 6]));Run Code Online (Sandbox Code Playgroud)
您还可以使用 call直接在参数上调用reduce:
Array.prototype.reduce.call(arguments, function(acc, curr) {
// ...
});
Run Code Online (Sandbox Code Playgroud)
上面的代码使您的代码运行,但它不会产生测试时的正确输出:
if (acc[item] === undefined)
Run Code Online (Sandbox Code Playgroud)
不做你想做的事。您需要做的是记住每个值,并且仅将其推送到acc(如果以前没有见过):
Array.prototype.reduce.call(arguments, function(acc, curr) {
// ...
});
Run Code Online (Sandbox Code Playgroud)
其他一些方法:
if (acc[item] === undefined)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4127 次 |
| 最近记录: |