如何计算JavaScript数组中的字符?

时间:2016-06-13 19:47:44

标签: javascript arrays character counting

我需要计算数组中a到z的字符。

例如,我有一个这样的数组:

["max","mona"]

期望的结果将是这样的:

a = 2,m = 2,n = 1,o = 1,x = 1

如果有人能帮助我,那将会很棒。)

6 个答案:

答案 0 :(得分:4)

You can use two forEach loops and return object

var ar = ["max", "mona"], o = {}

ar.forEach(function(w) {
  w.split('').forEach(function(e) {
    return o[e] = (o[e] || 0) + 1;
  });
});

console.log(o)

Or with ES6 you can use arrow function

var ar = ["max","mona"], o = {}

ar.forEach(w => w.split('').forEach(e => o[e] = (o[e] || 0)+1));
console.log(o)

As @Alex.S suggested you can first use join() to return string, then split() to return array and then you can also use reduce() and return object.

var ar = ["max", "mona"];

var result = ar.join('').split('').reduce(function(o, e) {
  return o[e] = (o[e] || 0) + 1, o
}, {});
console.log(result)

答案 1 :(得分:2)

您只能使用一个forEach循环并返回对象

var ar = [ "bonjour", "coucou"], map = {};
ar.join("").split("").forEach(e => map[e] = (map[e] || 0)+1);
console.log(map);

现场演示

https://repl.it/C17p

答案 2 :(得分:1)

我会这样做;



var     a = ["max","mona"],
charCount = a.reduce((p,w) => w.split("").reduce((t,c) => (t[c] ? t[c]++: t[c] = 1,t),p),{});
console.log(charCount);




答案 3 :(得分:1)

public static void main (String[] args) throws java.lang.Exception
{
    String[] original = {"The","Quick","Brown","Fox","Jumps","Over","The","Lazy","Dog"};
    String singleString ="";
    for(String str : original )
    {
        singleString += str;
    }
     System.out.println(singleString);
    char[] chars = singleString.toLowerCase().toCharArray();
    Arrays.sort(chars);
    String result="";

    for(int i=0;i<chars.length;)
    {
    result += chars[i]+"=";
        int count=0;
        do {
            count++;
            i++;
            } while (i<chars.length-1 && chars[i-1]==chars[i]);

        result += Integer.toString(count)+",";

    }
    System.out.println(result.substring(0,result.length()-1));
}

答案 4 :(得分:0)

使用Array.joinArray.sortString.split函数的解决方案:

var arr = ["max","mona"],
    counts = {};

arr = arr.join("").split(""); // transforms the initial array into array of single characters
arr.sort();
arr.forEach((v) => (counts[v] = (counts[v])? ++counts[v] : 1));

console.log(counts);  // {a: 2, m: 2, n: 1, o: 1, x: 1}

答案 5 :(得分:-1)

试试这个:

var words = ['max', 'mona'],
    output = {};
    words.forEach(function(word){ 
    for(i=0; i < word.split('').length; i++){
    if(output[word[i]])
      output[word[i]] += 1;
    else{
      output[word[i]] = 1;
    }  
  } 
});

ps:抱歉没有格式化的代码,我还是习惯了编辑器=)