Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
142
rated 0 times [  144] [ 2]  / answers: 1 / hits: 62962  / 12 Years ago, wed, july 25, 2012, 12:00:00

I have an array as follows,



var arr = ['ab','pq','mn','ab','mn','ab']


Expected result



arr['ab'] = 3
arr['pq'] = 1
arr['mn'] = 2


Tried as follows,



$.each(arr, function (index, value) {
if (value)
arr[value] = (resultSummary[value]) ? arr[value] + 1 : 1;
});

console.log(arr.join(','));

More From » jquery

 Answers
112

no need to use jQuery for this task — this example will build an object with the amount of occurencies of every different element in the array in O(n)



var occurrences = { };
for (var i = 0, j = arr.length; i < j; i++) {
occurrences[arr[i]] = (occurrences[arr[i]] || 0) + 1;
}

console.log(occurrences); // {ab: 3, pq: 1, mn: 2}
console.log(occurrences['mn']); // 2



Example fiddle







You could also use Array.reduce to obtain the same result and avoid a for-loop



var occurrences = arr.reduce(function(obj, item) {
obj[item] = (obj[item] || 0) + 1;
return obj;
}, {});

console.log(occurrences); // {ab: 3, pq: 1, mn: 2}
console.log(occurrences['mn']); // 2



Example fiddle



[#84053] Monday, July 23, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
robertjaysona

Total Points: 276
Total Questions: 110
Total Answers: 116

Location: Finland
Member since Sat, Nov 6, 2021
3 Years ago
;