How To Get Repeated Objects In Json Array In Javascript
I have a JSON array like this : var data = [ {title: 'HH02'}, {title: 'HH03'}, {title: 'HH04'}, {title: 'HH02'}, {title: 'HH07'}, {title: 'HH08'
Solution 1:
You can use reduce, filter and map
- Group all the values by
title
first, count there repetition - Filter the
titles
which appears once or less then once ( exclude them ) - map them to get desired output
var data = [{title: "HH02"},{title: "HH03"},{title: "HH04"},{title: "HH02"},{title: "HH07"},{title: "HH08"},{title: "HH08"},{title: "HH10"},{title: "HH02"},{title: "HH11"}]
let final = [...data.reduce((op, inp) => {
let title = inp.title
op.set(title, (op.get(title) || 0) + 1)
return op
}, newMap()).entries()].filter(([_,repeat]) => repeat > 1).map(([title, repeat]) => ({
title,
repeat
}))
console.log(final)
Solution 2:
You can use lodash groupBy for that.
Here is the link https://lodash.com/docs/4.17.15#groupBy
It will return a JSON object with titles as key and the array of items under that key as its value.
The length of that value will return the required count.
Solution 3:
I would never suggest having side effects in a sort callback other than sorting the array itself. Try a reduce followed by a filter and map on Object.keys(...)
:
const countMap = data.reduce((result, element) => {
result[element.title] = (result[element.title] || 0) + 1;
return result;
}, {});
const result = Object.keys(countMap).filter(title => countMap[title] > 1).map(title => {
return {title, repeat: countMap[title]};
});
Solution 4:
You can count repeated objects with reduce
and filter them out with filter
Object.values(data.reduce((acc, value) => {
const repeat = acc[value.title] ? acc[value.title].repeat + 1 : 1;
acc[value.title] = { repeat: repeat, ...value };
return acc;
}, {})).filter(value => value.repeat > 1);
Post a Comment for "How To Get Repeated Objects In Json Array In Javascript"