Travis Michael Heller Travis Michael Heller - 1 year ago 58
Javascript Question

Create a new array from an existing array that holds the count for how many times an item exist using javascript/jquery

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:

var result = count(countryCodes);
console.log(result[0]+": "+result[1]);
function count(arr) {
var a = [], b = [], prev;
for ( var i = 0; i < arr.length; i++ ) {
if ( arr[i] !== prev ) {
} else {
prev = arr[i];
return [a, b];

Answer Source

Open console when press run button.

var arr = ['a', 'a', 'a', 'b', 'c', 'c', 'd', 'e', 'f', 'f', 'f', 'f'];

function getObjectFromArray(a) {
  var result = [],
      alreadyAdded = [];
  a.forEach(function(item) {
    var key = item,
      obj = {};
    if (alreadyAdded.indexOf(item) != -1) return;
    obj[key] = getCount(a, item)

  return result;

function getCount(a, el) {
  var count = 0;
  a.forEach(function(element) {
    if (element == el) count++

  return count;


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download