# 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.

+3

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 .

+9

source

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;
```

```
+5

source

Based on another answer 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;
}

```

```
+2

source

You can use array_count_values:

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

```

Output:

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

```
+1

source

All Articles