1

I have array of objects

const data=[
  {typeId: 1, sort: 1, name: "Test1"},
  {typeId: 2, sort: 1, name: "Test2"},
  {typeId: 1, sort: 2, name: "Test3"},
  {typeId: 3, sort: 1, name: "Test4"},
];

I want to remove duplicates by key "typeId" and key "sort" value is bigger. And i want add key "count" - how many times object duplicate by typeId.

This is what I want to achieve:

const answer=[
  {typeId: 1, sort: 1, name: "Test1", count: 2},
  {typeId: 2, sort: 1, name: "Test2", count: 1},
  {typeId: 3, sort: 1, name: "Test4", count: 1},
];

How can I do that?

0

2 Answers 2

2

This approach will work with any value for sort.

const data = [
  {typeId: 1, sort: 1, name: "Test1"},
  {typeId: 2, sort: 1, name: "Test2"},
  {typeId: 1, sort: 2, name: "Test3"},
  {typeId: 3, sort: 1, name: "Test4"},
];

const answer = Object.values(data.reduce((p, v) => {
  const old = p[v.typeId];
  if (!old)
    p[v.typeId] = { ...v, count: 1 };
  else if (old.sort > v.sort)
    p[v.typeId] = { ...v, count: old.count + 1 };
  else
    p[v.typeId].count++;
  return p;
}, {}));

console.log(answer);

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

Comments

2

You could take an object for grouping by typeId and increment count.

This approch assumes, that the smallest value of sort is always one.

const 
    data = [{ typeId: 1, sort: 1, name: "Test1" }, { typeId: 2, sort: 1, name: "Test2" }, { typeId: 1, sort: 2, name: "Test3" }, { typeId: 3, sort: 1, name: "Test4" }],
    result = Object.values(data.reduce((r, o) => {
        if (r[o.typeId]) r[o.typeId].count++;
        else r[o.typeId] = { ...o, sort: 1, count: 1 };
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.