Last active: 3 years ago
Remove array duplicates
const arr = [
{
message: 'Hello',
messageID: 1,
},
{
message: 'Hello',
messageID: 1,
},
{
message: 'World',
messageID: 2,
}
]
const removeDuplicates = (arr) => {
const _obj = {}
arr.forEach(item => {
_obj[item.messageID] = item
})
return Object.values(_obj)
}
const noDuplicates = removeDuplicates(arr)
console.log(noDuplicates)
type Msg = {
message: string,
messageID: number
}
const arr:Msg[] = [
{
message: 'Hello',
messageID: 1,
},
{
message: 'Hello',
messageID: 1,
},
{
message: 'World',
messageID: 2,
}
]
const removeDuplicates = (arr: Msg[]) => {
const _obj: {
[key: number]: Msg
} = {}
arr.forEach(item => {
_obj[item.messageID] = item
})
return Object.values(_obj)
}
const noDuplicates = removeDuplicates(arr)
console.log(noDuplicates)