-2

Currently, I got an array like that:

 uniqueCount = [a,a,b,c,d,a,a];

How can I count how many a,b,c are there in the array? I want to have a result like with format of array of object:

[{key: "a", count: 4}
 {key: "b", count: 1}
 {key: "c", count: 1}
 {key: "d", count: 1}]

Mycode :

var current = null;
var count = 0;
 for (var i = 0; i < uniqueCount .length; i++) {
    if (uniqueCount [i] != current) {
      if (count > 0) {
        result.push({
          key: current,
          count: count
        });
      }
      current = uniqueCount [i];
      count = 1;
    } else {
      count++;
    }
  }
  if (count > 0) {
    result.push({
      key: current,
      count: count
    });
  }

But the result:

[{key: "a", count: 2}
 {key: "b", count: 1}
 {key: "c", count: 1}
 {key: "d", count: 1}
 {key: "a", count: 2}]

Thanks you .

CDN
  • 394
  • 6
  • 15

5 Answers5

2

Reduce the array to a Map, and then use Array.from() to convert to an array of objects:

const array = ['a', 'a', 'b', 'c', 'd', 'a', 'a']

const count = Array.from(
  array.reduce((r, c) => r.set(c, (r.get(c) || 0) + 1), new Map()), 
  (([key, count]) => ({ key, count }))
)

console.log(count)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

You just need to apply condition properly, Check this snippet, First, we find in array by its name f.key === m. If found then increase it to 1 (uniqueArray[index].count += 1) else add into object with count 1.

const array = ['a', 'a', 'b', 'c', 'd', 'a', 'a'];

const uniqueArray = [];
array.forEach((m) => {
  const obj = { key: m, count: 1 };
  const index = uniqueArray.findIndex((f) => { return f.key === m; });
  index === -1 ? uniqueArray.push(obj) : uniqueArray[index].count += 1;
});


console.log(uniqueArray)
Neel Rathod
  • 2,013
  • 12
  • 28
0
    uniqueCount = ["a","a","b","c","d","a","a"]
    count = {}
    uniqueCount.forEach(x => {
       if(count[x]) {
           count[x] += 1
       }
        else {
           count[x] = 1
        }
    })
    const result = Object.keys(count).map(x => { return {key:x, count:count[x]}})
    console.log(result)
Srinivas
  • 294
  • 3
  • 18
0

First count the character number of occurrence in uniqueCount array. Then make the resulting array of object using map as below

var uniqueCount = ['a','a','b','c','d','a','a'];
var duplicateCount = {};
uniqueCount.forEach(e => duplicateCount[e] = duplicateCount[e] ? duplicateCount[e] + 1 : 1);
var result = Object.keys(duplicateCount).map(e => {return {key:e, count:duplicateCount[e]}});
console.log(result);
Harun Or Rashid
  • 5,589
  • 1
  • 19
  • 21
0

You should use lodash to work with complicated data transformation like your goal:

console.log(
  _.chain(uniqueCount)
  .groupBy()
  .map((value, key) => ({ key: key, count: value.length}))
  .value()
);

Lodash document: https://lodash.com/docs/4.17.15

thelonglqd
  • 1,805
  • 16
  • 28