计算数组中字符串的出现次数

时间:2019-03-26 06:01:54

标签: javascript arrays

需要计算数组中字符串的出现次数

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

需要获取每个字符串的数量

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

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

2 个答案:

答案 0 :(得分: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);

希望这对您有帮助!

答案 1 :(得分:0)

您可以将Array#reduce方法与保留对象索引的引用对象一起使用。

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)