我无法使用filter()来生成唯一数组,不确定以下逻辑的错误。
https://jsbin.com/mufobevezo/edit?js,console,output
var uniqueProducts = json.filter(function(elem, i, array) {
return array.indexOf(elem) === i;
}
);
console.log(uniqueProducts);
我从这里获取的代码https://danmartensen.svbtle.com/javascripts-map-reduce-and-filter。不确定indexOf在示例中做了什么。
我只是想知道上面的链接是否有错误。
答案 0 :(得分:1)
我只是想知道上面的链接是否有错误。
不确定indexOf在示例中做了什么。
好的。让我们看一下代码:
var uniqueProducts = json.filter(function(elem, i, array) {
return array.indexOf(elem) === i;
}
);
console.log(uniqueProducts);
假设你有这个数组:[5,2,3,5]
filter
功能将运行4次。
[5,2,3,5].indexOf(5) === 0;
// true,过滤器将返回true
[5,2,3,5].indexOf(2) === 1;
// true,过滤器将返回true
[5,2,3,5].indexOf(3) === 2;
// true,过滤器将返回true
[5,2,3,5].indexOf(5) === 3;
// false(!)。 (5)的索引是第一个索引,它是0而不是3,因此函数返回false。所以看看刚刚发生了什么,之前找到的元素没有被添加到集合中(因此删除了dup)。
所以你所拥有的只是5,2,3,这是数组的唯一编号。
更好?
答案 1 :(得分:0)
我认为这种方法对你有用。
Array.prototype.unique = function() {
var tmp = {},
out = [];
for (var i = 0, n = this.length; i < n; ++i) {
if (!tmp[this[i]]) {
tmp[this[i]] = true;
out.push(this[i]);
}
}
return out;
}
答案 2 :(得分:0)
你可以创建一个小哈希并检查它。
https://jsbin.com/pujuvadaxi/edit?js,console,output
var json = [
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}
]
var tmp ={};
var uniqueProducts = json.filter(function(elem) {
var exists = tmp[JSON.stringify(elem)];
if (!exists) {
tmp[JSON.stringify(elem)]=true;
}
return !exists;
}
);
console.log(uniqueProducts);