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()
huysentruitw
  • 27,376
  • 9
  • 90
  • 133
archvist
  • 712
  • 2
  • 18
  • 41

2 Answers2

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/>");
Jorrex
  • 1,503
  • 3
  • 13
  • 32
  • What if I want the results stored in a variable I don't want to output them in html – archvist Jan 05 '16 at 15:51
  • use the shorter way, this will give you an object with properties. Such a property could be "Apple" which has a value of 3. – Jorrex Jan 05 '16 at 15:54
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>
jcubic
  • 61,973
  • 54
  • 229
  • 402