Travis Michael Heller Travis Michael Heller - 7 months ago 12
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:

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];
}

Answer

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;
    alreadyAdded.push(item)
    obj[key] = getCount(a, item)
    result.push(obj)
  })

  return result;
}

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

  return count;
}

console.log(getObjectFromArray(arr))