-3

Need to count the occurences of string in an array

userList=["[email protected]","[email protected]","[email protected]"]

Need to get the count of each strings

let userList=["[email protected]","[email protected]","[email protected]"]

Expected : [{"[email protected]":2},{"[email protected]":1}]

Mark
  • 90,562
  • 7
  • 108
  • 148
ReNinja
  • 543
  • 2
  • 10
  • 27

2 Answers2

1
var userList=["[email protected]","[email protected]","[email protected]"];

var result = Object.values(userList.reduce((acc, c)=>{
    if(!acc.hasOwnProperty(c)) { acc[c] = {[c]:0};}
    acc[c][c] += 1; 
    return acc;
}, {}));

console.log(result);

Hope this helps you !

Saurabh Yadav
  • 3,303
  • 1
  • 10
  • 20
0

You can use Array#reduce method with a reference object which keeps the index of the element.

let userList = ["[email protected]", "[email protected]", "[email protected]"];

let ref = {};

let res = userList.reduce((arr, s) => (s in ref ? arr[ref[s]][s]++ : arr[ref[s] = arr.length] = { [s]: 1 }, arr), [])



console.log(res)



// or the same with if-else

// object for index referencing
let ref1 = {};

// iterate over the array
let res1 = userList.reduce((arr, s) => {
  // check if index already defined, then increment the value
  if (s in ref1)
    arr[ref1[s]][s]++;
  // else create new element and add index in reference array
  else
    arr[ref1[s] = arr.length] = { [s]: 1 };
  // return array reference
  return arr;
  // set initial value as empty array for result
}, []);

console.log(res1)
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188