1

I'm trying to display the contents of my array but where duplicates exist just print the name and the number e.g

myArr = ['apple', 'apple', 'orange', 'apple', 'banana', 'orange', 'pineapple']

Would display;

apple 3
orange 2
banana
pineapple

So far I'm returning them all as a string:

arrList = myArr.join(', ');
arrList.toString()
1
  • Create an object with keys as the array elements and value as the count Commented Jan 5, 2016 at 15:39

2 Answers 2

8

The long way

var elements = ["apple", "apple", "orange", "apple", "banana"];

elements.sort();

var current = null;
var count = 0;

for(var i = 0; i < elements.length; i++)
{
    if(elements[i] != current)
  {
    if(count > 0)
    {
        document.write(current + " " + count + "<br/>");
    }
    current = elements[i];
    count = 1;
  }
  else
  {
    count++;
  }
}

if(count > 0)
{
    document.write(current + " " + count);

The short way

var elements = ["apple", "apple", "orange", "apple", "banana"];

var counts = {};

elements.forEach(function(x) {
    counts[x] = (counts[x] || 0) + 1;
});

document.write("Apple: " + counts.apple + "<br/>");
document.write("Banana: " + counts.banana + "<br/>");
document.write("Orange: " + counts.orange + "<br/>");
Sign up to request clarification or add additional context in comments.

2 Comments

What if I want the results stored in a variable I don't want to output them in html
use the shorter way, this will give you an object with properties. Such a property could be "Apple" which has a value of 3.
2

Try this:

var myArr = ['apple', 'apple', 'orange', 'apple', 'banana', 'orange', 'pineapple'];
var obj = {};
myArr.forEach(function(item) {
  if (typeof obj[item] == 'number') {
    obj[item]++;
  } else {
    obj[item] = 1;
  }
});
document.getElementById('output').innerHTML = Object.keys(obj).map(function(item) {
  return item + (obj[item] == 1 ? '' : ' ' + obj[item]);
}).join('\n');
<pre id="output"></pre>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.