0

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
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
Yogesh
  • 331
  • 1
  • 4
  • 10

2 Answers2

0

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);
random
  • 7,756
  • 3
  • 19
  • 25
0

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)
ellipsis
  • 12,049
  • 2
  • 17
  • 33