I have a list of items in an array and i want to create a new array that is an array of objects with the key being the value from the existing array and the value being the number of times that item was in the existing array. Hope that makes since, if not hopefully this example will help. No third party libraries like lodash or underscore please.
Any help would be greatly appreciated, thank you.
var arr = [a,a,a,b,c,c,d,e,f,f,f,f];
new array =[{a:3},{b:1},{c:2},{d:1},{e:1},{f:4}];
My attempt so far:
countryCodes.sort();
var result = count(countryCodes);
console.log(result[0]+": "+result[1]);
function count(arr) {
var a = [], b = [], prev;
arr.sort();
for ( var i = 0; i < arr.length; i++ ) {
if ( arr[i] !== prev ) {
a.push(arr[i]);
b.push(1);
} else {
b[b.length-1]++;
}
prev = arr[i];
}
return [a, b];
}
var arr = ['a', 'a', 'a', 'b', 'c', 'c', 'd', 'e', 'f', 'f', 'f', 'f']; var count = {}; arr.forEach(function (e) { count[e] = count[e] ? ++count[e] : 1; }); var res = []; Object.keys(count).forEach(function (key) { res.push({ [key]: count[key] }); }); console.log(res);