javascript - How to count duplicate words in array and add a count number to EACH word? -
my goal turn
['sara', 'mike', 'sara','sara','jon']
into
'sara', 'mike', 'sara(1)','sara(2)' 'jon'
ive seen solutions when counting total number of duplicates, however, couldnt find trying do..
ps. cannot use sort() names should stay in original array..
i tried using regular loop nothing worked, think map approach good, cant figure out how that.
thank you!
edit:
i came here:
function words(arr){ var result=[]; var count=0; (var i=0; i<arr.length; i++){ if (result.indexof(arr[i])==-1){ result.push(arr[i]); } else { count++; result.push(arr[i]+"("+count+")"); } } return result.join(','); } words(['sara', 'mike', 'sara','sara','jon'] );
and works except returns 'sara,mike,sara(1),sara(2),jon' instead of 'sara','mike,'sara(1)','sara(2)','jon'
anyone knows how change that? tried join, split etc already..
try this:
function countwords (words) { var wordscounter = {}, results = []; words.foreach(function (word) { if (!wordscounter.hasownproperty(word)) { results.push(word); wordscounter[word] = 1; } else { results.push(word + '(' + (wordscounter[word]++) + ')'); } }); return results; }