3

I need to count the characters from a to z in an array.

For example I have an array like this:

["max","mona"]

The desired result would be something like this:

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

1

6 Answers 6

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)

Sign up to request clarification or add additional context in comments.

4 Comments

The return isn't needed in the first one. forEach doesn't do anything with what is returned.
Also, this algorithm can be found at the near-duplicate question Counting the occurrences of JavaScript array elements
Maybe we can use join to avoid outer forEach. Like: ar.join().split('').forEach()
We can also add .sort() to get the desired result.
2

You can use just one forEach loop and return object

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

Live Demo

https://repl.it/C17p

Comments

1

I would do it like this;

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);

Comments

1

Convert your array to a string using the join method and then use the length property of a string-

like:

arr.join('').length

Comments

0

The solution using Array.join, Array.sort and String.split functions:

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}

Comments

-1

Try this:

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;
    }  
  } 
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.