Reputation: 1
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"}]
Upvotes: 0
Views: 91
Reputation: 18515
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]], []))
Upvotes: 0
Reputation: 4636
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)
Upvotes: 1
Reputation: 370669
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)
);
Upvotes: 2