I want to find the duplicate values from array and its occurrences:-
const names = ['John', 'Paul',, 'Paul', 'Paul' 'George', 'John'];
it should print:-
john - 2
Paul - 3
George - 1
I want to find the duplicate values from array and its occurrences:-
const names = ['John', 'Paul',, 'Paul', 'Paul' 'George', 'John'];
it should print:-
john - 2
Paul - 3
George - 1
use reduce
. Create object which has keys as name
and it's occurrence (count) as a value.
const names = ['John', 'Paul', 'Paul', 'Paul', 'George', 'John'];
const output = names.reduce((accu, name) => {
accu[name] = (accu[name] || 0) + 1;
return accu;
}, {});
console.log(output);
Using map and filter
var a= ['John', 'Paul', 'Paul', 'Paul' ,'George', 'John'];
var obj={};
a.map(e=>{
obj[e]=a.filter(x=>x==e).length;
})
console.log(obj)