0

I have a JSON object

var data = [
{totalTime: 67, phoneNo: "400-234-090"}, 
{totalTime: 301, phoneNo: "701-080-080"}, 
{totalTime: 300, phoneNo: "400-234-090"}
]

I want to remove duplicate object. Please guide. Output should be as below one

var data = [{totalTime: 301, phoneNo: "701-080-080"}] 
3
  • @Daniel This is not a duplicate of that. OP wants to remove all the duplicates from the array, not just keep all the unique ones. Commented Aug 2, 2018 at 2:24
  • Example which you have mentioned is not removing duplicate record. It is just removing occurrence. I need unique records. Commented Aug 2, 2018 at 2:34
  • @Andy did any of the answers bellow solve your problem? If so you should mark the answer. It helps others etc. Commented Aug 2, 2018 at 17:42

3 Answers 3

2

For a solution with low complexity, I'd first make an object that counts the occurences of each phoneNo, and then filter the input by the count of each object's number being 1:

var data = [
  {totalTime: 67, phoneNo: "400-234-090"}, 
  {totalTime: 301, phoneNo: "701-080-080"}, 
  {totalTime: 300, phoneNo: "400-234-090"}
];
const phoneCounts = data.reduce((a, { phoneNo }) => {
  a[phoneNo] = (a[phoneNo] || 0) + 1;
  return a;
}, {});
console.log(
  data.filter(({ phoneNo }) => phoneCounts[phoneNo] === 1)
);

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

3 Comments

@Andy When an answer solves your problem, you can consider marking it as Accepted to indicate that the issue is resolved
@CertainPerformance can you please guide me how to accept the answer
You can see here: click on the check mark beside the answer to toggle it from greyed out to filled in.
1

You can just use two filters such that, we will only select objects that are just single entry in the array

const data = [
  {totalTime: 67, phoneNo: "400-234-090"}, 
  {totalTime: 301, phoneNo: "701-080-080"}, 
  {totalTime: 300, phoneNo: "400-234-090"}
]

const newData = data.filter(outer => 
  data.filter(inner => 
    outer.phoneNo === inner.phoneNo
  ).length === 1
)

console.log(newData)

2 Comments

This has O(N^2) complexity... not important in small datasets, but probably not preferable regardless
@CertainPerformance yes O(n^2) indeed. But has less space complexity as well :)
0

Another option (1 reduce, 1 filter and spread):

var data = [
{totalTime: 67, phoneNo: "400-234-090"}, 
{totalTime: 301, phoneNo: "701-080-080"}, 
{totalTime: 300, phoneNo: "400-234-090"}
];

console.log(data.reduce((x, { phoneNo }, i, a) => 
  a.filter((y) => 
	y.phoneNo === phoneNo).length > 1 ? x : [...x, a[i]], []))

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.