1

I'm learning javascript and I have some problems. I would like to iterate an array of objects but with a few "options":

  • don't display duplicate items.
  • display the number of items.

expected result :

received 1

missed 2

dialed 3

I know how to iterate a array of objects and use .length to display the quantity of each item but I don't know iterate + display quantity + remove duplicates... Can you help me ?

const calls = [
  {
    type: "missed",
    date: "xx-xx-xx"
  },
  {
    type: "received",
    date: "xx-xx-xx"
  },
  {
    type: "dialed",
    date: "xx-xx-xx"
  },
  {
    type: "missed",
    date: "xx-xx-xx"
  },
  {
    type: "dialed",
    date: "xx-xx-xx"
  },
  {
    type: "dialed",
    date: "xx-xx-xx"
  }
];

3 Answers 3

1

A good way to group items is with reduce (it’s also flexible, so if you add another type it works no problem):

const calls = [{
    type: "missed",
    date: "xx-xx-xx"
  },
  {
    type: "received",
    date: "xx-xx-xx"
  },
  {
    type: "dialed",
    date: "xx-xx-xx"
  },
  {
    type: "missed",
    date: "xx-xx-xx"
  },
  {
    type: "dialed",
    date: "xx-xx-xx"
  },
  {
    type: "dialed",
    date: "xx-xx-xx"
  }
];

const output = calls.reduce((aggObj, item) => {
    if(!aggObj[item.type]){
        aggObj[item.type] = 0
    }
    aggObj[item.type] += 1;
    return aggObj;
}, {});
//output as object:
console.log(output);

//output as array:
const outArr = Object.entries(output);
console.log(outArr);

//output as strings:
outArr.forEach(([k,v]) => console.log(k,v));

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

Comments

0

const calls = [{
    type: "missed",
    date: "xx-xx-xx"
  },
  {
    type: "received",
    date: "xx-xx-xx"
  },
  {
    type: "dialed",
    date: "xx-xx-xx"
  },
  {
    type: "missed",
    date: "xx-xx-xx"
  },
  {
    type: "dialed",
    date: "xx-xx-xx"
  },
  {
    type: "dialed",
    date: "xx-xx-xx"
  }
];
const types = ["missed", "received", "dialed"];
types.forEach(type => {
  console.log(type + ": " + calls.filter((calls) => calls.type === type).length);
});

Comments

0

i hope this helps

var newArr = calls.filter((x, index, self) =>
  index === self.findIndex((t) => (
    t.type === x.type && t.date === x.date)));

console.log(newArr);

Comments

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.