0

I have an Array of string elements and I need to find how many times a elements occured in a Array. my Array is following: var x=["water","water","water","land", "land","land","land","forest"];

I need to know which element is prominent in Array. I have tried to use example from this discussion "Counting the occurrences of JavaScript array elements". But I did not get any expected result. Please help me to find a possible solution. :-)

Community
  • 1
  • 1
Shiuli Pervin
  • 125
  • 2
  • 8

1 Answers1

0

There may not be an unambiguous answer to which item occurs the most times. Here is how you can get the item counts in a functional style:

x.reduce(function(counts, key) { 
  if(!counts.hasOwnProperty(key))
    counts[key] = 0
  counts[key] = counts[key] + 1
  return counts }, {})

Returns {"water": 3, "land": 4, "forest": 1}

tpatja
  • 690
  • 4
  • 11
  • May be I am doing some mistake in my steps. Could you please take a look of my codes:'var x=["water","water","water","land", "land","land","land","forest"]; var counts = {}; x.reduce(function(counts, key) { if(!counts.hasOwnProperty(key)) counts[key] = 0; counts[key] = counts[key] + 1; return counts; },{}); alert(counts);' It Shows code is valid but Returns like this:[objectobject] --Thanks a lot:-) – Shiuli Pervin May 15 '14 at 12:36
  • It returns a javascript object with the items as keys. You can get a readable string representation with JSON.stringify(x) – tpatja May 15 '14 at 12:52