Отображение количества элементов из массива объектов без дубликатов - PullRequest
1 голос
/ 16 июня 2020

Я учусь javascript и у меня проблемы. Я хотел бы перебрать массив объектов, но с несколькими «параметрами»:

  • не отображать повторяющиеся элементы.
  • отображать количество элементов.

ожидаемый результат:

received 1

missed 2

dialed 3

Я знаю, как перебирать массив объектов и использовать .length для отображения количества каждого элемента, но я не знаю, как повторить + отобразить количество + удалить дубликаты ... Вы можете мне помочь?

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 ]

1 голос
/ 16 июня 2020

Хороший способ группировки элементов - это сокращение (он также гибкий, поэтому, если вы добавите другой тип, это не сработает):

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));
0 голосов
/ 16 июня 2020

надеюсь, это поможет

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

console.log(newArr);
0 голосов
/ 16 июня 2020

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