ndcomix ndcomix - 3 months ago 68
Javascript Question

Lodash: Convert array with duplicate values to object with number of repeated occurrences

Here is my array:

['California','Texas','Texas','Texas','New York','Missouri','New Mexico','California']


Is there a way in lodash to convert it to an object with a count of repeated occurrences like this:

[
{'name':'California', 'count':2},
{'name':'Texas', 'count':3},
{'name':'New York', 'count':1},
{'name':'Missouri', 'count':1},
{'name':'New Mexico', 'count':1},
]


I have tried many combinations but have not been successful. Docs: https://lodash.com/docs#countBy

Answer

You could just map the result of _.countBy.

var array = ['California','Texas','Texas','Texas','New York','Missouri','New Mexico','California'],
    count = _.countBy(array),
    result = _.map(count, (v, k) => ({ name: k, count: v }));

console.log(count);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

Combined with _.chain

var array = ['California','Texas','Texas','Texas','New York','Missouri','New Mexico','California'],
    count = _
        .chain(array)
        .countBy()
        .map((v, k) => ({ name: k, count: v }));

console.log(count);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>