Pergunta

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. :-)

Foi útil?

Solução

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}

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top