1

so i have an array like this, that i want to find the unique value with then count:

users: 
   [ '21000316',
     '21000316',
     '21000316',
     '21000316',
     '22000510',
     '22000510',
     '22000510',
     '22000510' ]

is it possible for me to get the unique value and count it from the array without using sort()? and turn it into this value i try some code but only get the count and the unique value separetely:

{'21000316':4,'21000510':4}
JS24
  • 1
  • 2
  • 14

3 Answers3

2

Probably a better approach but you can create an object and then sort through all array elements adding +1 to the object.

const users = ['1', '1', '2', '3', '3', '3', '3'];
const result = {};

for(const user in users)
  result[users[user]] = (result[users[user]] || 0) + 1;

console.log(result);
Finbar
  • 1,127
  • 1
  • 5
  • 17
1

const users = [
     '21000316',
     '21000316',
     '21000316',
     '21000316',
     '22000510',
     '22000510',
     '22000510',
     '22000510'
];
console.log(users.reduce((m, k) => { m[k] = m[k] + 1 || 1; return m }, {}));
Allan Wind
  • 23,068
  • 5
  • 28
  • 38
1

let users =  [ '21000316',
     '21000316',
     '21000316',
     '21000316',
     '22000510',
     '22000510',
     '22000510',
     '22000510' ];
     
let set = new Set(users);

let res = [...set.keys()].reduce((pre, cur) => {
    pre[cur] = users.filter(u => u === cur).length;
    return pre;
}, {})

console.log(res)