使用JS从JSON对象中删除重复值

时间:2019-07-17 07:49:02

标签: arrays angularjs

我有以下JSON对象

var array = [{"id":"1","date":"2019-01-20"},
        {"id":"1","date":"2019-01-20"},{"id":"1","date":"2019-01-21"},{"id":"2","date":"2019-01-20"},{"id":"2","date":"2019-01-19"},{"id":"2","date":"2019-01-20"},{"id":"2","date":"2019-03-20"},{"id":"3","date":"2019-01-20"},{"id":"3","date":"2019-03-19"},{"id":"3","date":"2019-01-19"},{"id":"3","date":"2019-05-20"}]

我想通过删除与每个ID相关的日期重复来获得以下输出

var outPut= [{"id":"1","date":"2019-01-20"},{"id":"1","date":"2019-01-21"},{"id":"2","date":"2019-01-20"},{"id":"2","date":"2019-01-19"},{"id":"3","date":"2019-01-20"},{"id":"3","date":"2019-03-19"}]

我编写了以下代码,该代码将删除重复的date值,但是它将删除两个不同id的相同日期,这是错误的。如何获得预期的输出?

const uniqueAddresses = Array.from(new Set(array.map(a => a.date)))
 .map(date=> {
   return addresses.find(a => a.date=== date)
 })

1 个答案:

答案 0 :(得分:1)

使用es6

var array = [{"id":"1","date":"2019-01-20"},
        {"id":"1","date":"2019-01-20"},{"id":"1","date":"2019-01-21"},{"id":"2","date":"2019-01-20"},{"id":"2","date":"2019-01-19"},{"id":"2","date":"2019-01-20"},{"id":"2","date":"2019-03-20"},{"id":"3","date":"2019-01-20"},{"id":"3","date":"2019-03-19"},{"id":"3","date":"2019-01-19"},{"id":"3","date":"2019-05-20"}]
        
var newArr = array.filter((curr, index, self) =>
  index === self.findIndex((elem) => (
    elem.id === curr.id && elem.date === curr.date
  ))
)

console.log(newArr);