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
. (because value === arr[i]
, so 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:
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
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.