2

I have a list of dates like this:

[ "2020-08-20", "2020-08-20", "2020-08-21", "2020-08-24", "2020-08-25", "2020-08-25", "2020-08-25", ]

how to return a count of the items in list which is this same?

for example:

{date: "2020-08-20", count: 2},
{date: "2020-08-21", count: 1},
{date: "2020-08-24", count: 1},
{date: "2020-08-25", count: 3},

thanks for any help

  • https://stackoverflow.com/questions/5667888/counting-the-occurrences-frequency-of-array-elements – epascarello Oct 27 '20 at 18:58
  • `Object.values([ "2020-08-20", "2020-08-20", "2020-08-21", "2020-08-24", "2020-08-25", "2020-08-25", "2020-08-25", ] .reduce((o, date) => (o[date] ? o[date].count++ : o[date] = { date, count: 1 }, o), {}));` – epascarello Oct 27 '20 at 19:24

3 Answers3

6

const ary = [ "2020-08-20", "2020-08-20", "2020-08-21", "2020-08-24", "2020-08-25", "2020-08-25", "2020-08-25", ] 

const result = []

ary.forEach(d => {
  const index = result.findIndex(r => r.date === d)
  if (index === -1) {
    result.push({
      date: d,
      count: 1
    })
  } else {
    result[index].count ++;
  }
})

console.log(result)
wangdev87
  • 8,611
  • 3
  • 8
  • 31
4

You can use array reduce method to count it. Traverse the string array and count the frequencies. At last print the result using Object.values method.

const data = [
  '2020-08-20',
  '2020-08-20',
  '2020-08-21',
  '2020-08-24',
  '2020-08-25',
  '2020-08-25',
  '2020-08-25',
];

const ret = data.reduce((prev, c) => {
  const p = prev;
  if (!p[c]) p[c] = { date: c, count: 1 };
  else p[c] = { date: c, count: p[c].count + 1 };
  return p;
}, {});
console.log(Object.values(ret));
mr hr
  • 3,162
  • 2
  • 9
  • 19
3

I think you could something like:

    const yourArray = [ "2020-08-20", "2020-08-20", "2020-08-21", "2020-08-24", "2020-08-25", "2020-08-25", "2020-08-25", ]
    const result = yourArray
      .filter((item, pos) => yourArray.indexOf(item) == pos)
      .map(item => ({
        date: item,
        count: yourArray.filter(current => current === item).length
      }))
    console.log(result)