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}
2

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

it return this :{ '2022-11-12': 1, '2022-11-14': 1 }
Refresh your answer
2

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

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.