[英]Using Array.prototype.filter() doesn't de-dupe array of arrays
I have the following data I'm trying to dedupe: 我要删除以下数据:
Actual 实际
var data = [
['dupeValue', { data: 123 }],
['dupeValue', { data: 123 }],
['otherValue', { data: 1111111 }],
['dupeValue', { data: 123 }]
]
Expected 预期
var data = [
['dupeValue', { data: 123 }],
['otherValue', { data: 1111111 }]
]
I tried the following, but doesn't work: 我尝试了以下操作,但不起作用:
data.filter((value, i, arr) => {
return value[0] !== arr[i][0]
})
// outputs []
What am I missing? 我想念什么?
var data = [ ['dupeValue', { data: 123 }], ['dupeValue', { data: 123 }], ['otherValue', { data: 1111111 }], ['dupeValue', { data: 123 }] ] var result = data.filter((value, i, arr) => { return value[0] !== arr[i][0] }) console.log(result)
Your filter test is 您的过滤器测试是
var result = data.filter((value, i, arr) => {
return value[0] !== arr[i][0]
});
But arr[i]
will always refer to the current element being iterated over - the value
, so no matter the input, value[0] !== arr[i][0]
will always evaluate to false
. 但是
arr[i]
将始终引用当前元素在- value
进行迭代,因此无论输入如何, value[0] !== arr[i][0]
始终将评估为false
。 (because value === arr[i]
, so value[0] === arr[i][0]
). (因为
value === arr[i]
,所以value[0] === arr[i][0]
)。
You might add the value[0]
to a Set
, and when testing, check whether that value exists in the set yet or not: 您可以将
value[0]
添加到Set
,并在测试时检查该值是否存在于set中:
var data = [ ['dupeValue', { data: 123 }], ['dupeValue', { data: 123 }], ['otherValue', { data: 1111111 }], ['dupeValue', { data: 123 }] ] const firstElements = new Set(); var result = data.filter(([firstElement]) => { const alreadyHas = firstElements.has(firstElement); firstElements.add(firstElement); return !alreadyHas; }) console.log(result)
You could use a reduce()
to map to an object and Object.values()
to get resultant array 您可以使用
reduce()
映射到对象,然后使用Object.values()
获得结果数组
var data = [ ['dupeValue', { data: 123 }], ['dupeValue', { data: 123 }], ['otherValue', { data: 1111111 }], ['dupeValue', { data: 123 }] ] var result = Object.values(data.reduce((a, c) => (a[c[0]] = c, a), {})) console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.