Convert array to new array (counting)
I have an array of n elements
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, 0, 0, 2, 1, 1, 1, 2, 2, 1, 0, 0, 0, 2, 2, 2, 2, 2, 1, 0, 2, 2, 0, 2, 2, 0, 2, 0, 0, 1, 2, 1, 0, 2, 1, 0, 1, 2, 0, 2, 0, 0, 0, 1, 2, 1, 0, 2, 0, 0, 0, 1, 2, 1, 1, 1, 1]
as you can see the array has i different values (v)
(0,1,2),i = 3
in this case
I would like to end up with an array like this.
var arr2 = [23, 45, 64]
the length of the arr2 array must match i , and the values ββcan be occurrences of each value(v)
I am doing all kinds of loops and conditionals but looking for a straight forward solution. my part so far http://jsfiddle.net/fiddlebjoern/aSsjy/2/
jQuery and / or underscore can be involved.
source to share
Easy peasy! The values ββof your input become the keys of your output; you accumulate these keys as values ββappear:
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 .
source to share
Sounds like a job to "reduce"
arr2 = arr1.reduce(function(a, v) {
a[v] = (a[v] || 0) + 1;
return a;
}, [])
Also, yours 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 emulation or use a library like underscore.js.
Example with underscore.js:
arr2 = _(arr1).chain().groupBy(_.identity).map(_.size).value()
It may not be as "easy" as the other answers, but at least you can learn something.
For the sake of being complete, here's the correct way to use a simple loop for the same task:
counter = [] // or {}
for (var i = 0; i < arr.length; i++)
counter[arr[i]] = (counter[arr[i]] || 0) + 1;
source to share