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"}] 
Andy
  • 1
  • 2
  • @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. – Blue Aug 02 '18 at 02:24
  • Example which you have mentioned is not removing duplicate record. It is just removing occurrence. I need unique records. – Andy Aug 02 '18 at 02:34
  • @Andy did any of the answers bellow solve your problem? If so you should mark the answer. It helps others etc. – Akrion Aug 02 '18 at 17:42

3 Answers3

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)
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
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)
Prasanna
  • 4,125
  • 18
  • 41
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]], []))
Akrion
  • 18,117
  • 1
  • 34
  • 54