JavaScript removes objects with the same key value from the object array

topic description

remove objects with the same key value from the object array

sources of topics and their own ideas

related codes

let arr = [
  {"weight":10,"id":1},
  {"weight":20,"id":2},
  {"weight":30,"id":2},
  {"weight":40,"id":4},
  {"weight":50,"id":5}
];

what result do you expect? What is the error message actually seen?

let arr = [
  {"weight":10,"id":1},
  {"weight":30,"id":2},
  {"weight":40,"id":4},
  {"weight":50,"id":5}
];
Aug.05,2021

let obj = {}
arr = arr.reduce((item, next) => {
  obj[next.id] ? '' : obj[next.id] = true && item.push(next)
  return item
}, [])
console.log(arr)

use the utility function, lodash uniqBy ,

const arr = [
  {"weight":10,"id":1},
  {"weight":20,"id":2},
  {"weight":30,"id":2},
  {"weight":40,"id":4},
  {"weight":50,"id":5}
]
_.uniqBy(arr, 'id')

if, according to the reference results provided, the data with an id of "2" appears twice and the value of the latter is actually taken, then the above answer is not correct.

let obj = {}
arr.map(item => {
  obj[item.id] = item
})
let result = Object.values(obj)

Don't forget that the data of the landlord is stored in an array, and the array itself is ordered, while the object key is unordered. So using native object key to remove weight is not the most suitable answer. Here is a possible answer

[...new Map(arr.map(({id, weight})=>([id, weight]))).entries()].map(([id, weight])=>({id, weight}))
Menu