Home > Software design >  find unique values in array and count javascript
find unique values in array and count javascript

Time:11-15

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}

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

const users = 
   [ '21000316',
     '21000316',
     '21000316',
     '21000316',
     '22000510',
     '22000510',
     '22000510',
     '22000510' ];
console.log(users.reduce((m, k) => { m[k] = m[k]   1 || 1; return m }, {}));

  • Related