0

I have a JSON array like this :

var data = [
      {title: "HH02"},
      {title: "HH03"},
      {title: "HH04"},
      {title: "HH02"},
      {title: "HH07"},
      {title: "HH08"},
      {title: "HH08"},
      {title: "HH10"},
      {title: "HH02"},
      {title: "HH11"}
]

First I would like to get repeated objects in JSON array like this:

var output = [
     {title: "HH02" },
     {title: "HH08" },
]

Then I would like to get all repeated objects and how many times they are repeated in another JSON array like this

var output = [
     {title: "HH02" , repeat: 3},
     {title: "HH08" , repeat: 2},
]

I tried doing this, but it didn't work well:

data.map(v => v.title).sort().sort((a, b) => {
                    if (a === b) output.push(a);
                })
1

4 Answers 4

2

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
}, new Map()).entries()].filter(([_,repeat]) => repeat > 1).map(([title, repeat]) => ({
  title,
  repeat
}))

console.log(final)

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

Comments

0

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.

Comments

0

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]};
});

Comments

0

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

1 Comment

You should add some commentary. Code-only answers are not good quality answers.

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.