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}))
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1bfba44-32291.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1bfba44-32291.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?