Reputation: 2536
An Array is as follows:
let names = [
'Aditya',
'Aditya',
'Aditya',
'Abhi',
'Abhi',
'goyal'
]
I want to use lodash function and convert the names array which will return me as
[
Aditya(3),
Abhi(2),
goyal(1)
]
Upvotes: 0
Views: 66
Reputation: 191986
You can use _.countBy()
to get an object of names with count, or a _.groupBy()
if you want an object of names with arrays.
An array of arrays using _.groupBy()
and _.values()
:
const names = ["Aditya","Aditya","Aditya","Abhi","Abhi","goyal"]
const result = _.values(_.groupBy(names))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
And object of counts with _.countBy
:
const names = ["Aditya","Aditya","Aditya","Abhi","Abhi","goyal"]
const result = _.countBy(names)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
Update - to get an array of strings that combine the key and value, you can use _.countBy()
, and then _.map()
it (lodash's _.map()
works on objects as well).
const names = ["Aditya","Aditya","Aditya","Abhi","Abhi","goyal"]
const result = _.map(_.countBy(names), (v, k) => `${k}(${v})`)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
Upvotes: 4
Reputation: 63524
1) _.countBy
the names to produce an object with name/count as the key/value.
2) Use _.entries
to convert the object to a set of nest entry arrays.
3) _.map
over the entries to produce the required output.
const names = ["Aditya","Aditya","Aditya","Abhi","Abhi","goyal"]
const toString = ([name, count]) => `${name}(${count})`;
const entries = _.entries(_.countBy(names));
const result = _.map(entries, toString);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
Alternatively you can use vanilla JS to achieve the same thing in (almost) the same amount of code using reduce
, Object.entries
, and map
.
const names = ["Aditya","Aditya","Aditya","Abhi","Abhi","goyal"]
const counts = names.reduce((acc, c) => {
return acc[c] = (acc[c] || 0) + 1, acc;
}, {});
const toString = ([name, count]) => `${name}(${count})`;
const entries = Object.entries(counts);
const result2 = entries.map(toString);
console.log(result2);
Upvotes: 1