Skip to content Skip to sidebar Skip to footer

Convert Array To New Array (counting Occurrences)

I have an array of n number of items var arr1 = [2, 0, 0, 1, 1, 2, 0, 0, 0, 2, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 2, 2, 0, 0, 2, 2, 1, 2, 2, 0, 1, 2, 2, 1, 1, 0, 1, 1, 0, 2, 1, 0,

Solution 1:

Easy peasy! The values of your input become the keys of your output; you accumulate on those keys as you encounter the values:

var arr1 = [0,0,0,1,2,3,4,3,2,3,4,3,4,3,5];
var arr2 = [];

for (var i = 0; i < arr1.length; i++) {
   var n = arr1[i];
   if (arr2[n] != undefined)
       arr2[n]++;
   else
       arr2[n] = 1;
}

console.log(arr2);  // Output: [3, 1, 2, 5, 3, 1]

Live demo.

Solution 2:

Sounds like a job for "reduce"

arr2 = arr1.reduce(function(a, v) {
    a[v] = (a[v] || 0) + 1;
    return a;
}, [])

Also, your arr2 is actually associative, so it's better to use an object instead:

map = arr1.reduce(function(a, v) {
    a[v] = (a[v] || 0) + 1;
    return a;
}, {})

reduce is Javascript 1.8, for older browsers you need an emulation or use a library like underscore.js.

Example with underscore.js:

arr2 = _(arr1).chain().groupBy(_.identity).map(_.size).value()

This is perhaps not so "easy" as other answers, but at least you can learn something from this.

For the sake of being complete, here's the correct way to use a plain loop for the same task:

counter = [] // or {}for (var i = 0; i < arr.length; i++)
     counter[arr[i]] = (counter[arr[i]] || 0) + 1;

Solution 3:

Based on the other answer, here's one that works:

var arr1 = [1,2,3,4,3,2,3,4,3,4,3,5];
var arr2 = [];
var n, m;

for (var i=0, iLen=arr1.length; i < iLen; i++) {
  n = arr1[i];
  m = arr2[n];
  arr2[n] = m? ++m : 1;
}

alert(arr2)

Solution 4:

You can use array_count_values:

<?php$array = array(1, "hello", 1, "world", "hello");
     print_r(array_count_values($array));
?>

The output is:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

Post a Comment for "Convert Array To New Array (counting Occurrences)"