0

I have the following JSON object

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"}]

And I want to have the following output by removing duplicates of date related to each 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"}]

I wrote the following code which will remove duplicate values of date but then it will remove the same date of two different ids which is wrong. how can I get the expected output?

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

1 Answer 1

1

Using 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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.