-3

Need to count the occurences of string in an array

userList=["abc@gmail.com","bca@gmail.com","abc@gmail.com"]

Need to get the count of each strings

let userList=["abc@gmail.com","bca@gmail.com","abc@gmail.com"]

Expected : [{"abc@gmail.com":2},{"bca@gmail.com":1}]

Mark
  • 90,562
  • 7
  • 108
  • 148
ReNinja
  • 543
  • 2
  • 10
  • 27
  • Oh nice yaar, please proceed – Krishna Prashatt Mar 26 '19 at 06:02
  • 1
    Show what you have tried so far – Alpesh Jikadra Mar 26 '19 at 06:03
  • 2
    Did you try searching before asking this question? – Phil Mar 26 '19 at 06:07
  • 1
    Possible duplicate of [Grouping js string array with counting](https://stackoverflow.com/questions/21549646) and [How to count the number of occurrences of each item in an array?](https://stackoverflow.com/questions/11649255) – adiga Mar 26 '19 at 06:08
  • Thanks @adiga, that's the one I was looking for – Phil Mar 26 '19 at 06:10
  • var userList = ["abc@gmail.com","bca@gmail.com","abc@gmail.com"]; var tmpObj = {}; for(var i = 0; i < userList.length; i++){ if(tmpObj[userList[i]]){ tmpObj[userList[i]]++; } else { tmpObj[userList[i]] = 1; } } var result = []; for(x in tmpObj){ var obj = {}; obj[x] = tmpObj[x]; result.push(obj); } console.log(result); – Adnan Toky Mar 26 '19 at 06:16

2 Answers2

1
var userList=["abc@gmail.com","bca@gmail.com","abc@gmail.com"];

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 = ["abc@gmail.com", "bca@gmail.com", "abc@gmail.com"];

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