Is it posible to count both name
and city
using one variable without using _.merge
?
const people = [
{ 'name': 'Adam', 'city': 'London', 'age': 34 },
{ 'name': 'Adam', 'age': 34 },
{ 'name': 'John', 'city': 'London','age': 23 },
{ 'name': 'Bob', 'city': 'Paris','age': 69 },
{ 'name': 'Mark', 'city': 'Berlin','age': 69 },
]
const names = _.countBy(people, (person) => person.name);
const cities = _.countBy(people, (person) => person.city);
console.log(_.merge(names,cities)); // Object {Adam: 2, Berlin: 1, Bob: 1, John: 1, London: 2, Mark: 1, Paris: 1, undefined: 1}
You don't need Lodash, simply use Array#Reduce
.
const people = [ { 'name': 'Adam', 'city': 'London', 'age': 34 }, { 'name': 'Adam', 'age': 34 }, { 'name': 'John', 'city': 'London','age': 23 }, { 'name': 'Bob', 'city': 'Paris','age': 69 }, { 'name': 'Mark', 'city': 'Berlin','age': 69 }, ] const result = people.reduce((acc, curr) => { acc[curr.name] = acc[curr.name] ? acc[curr.name] + 1 : 1; acc[curr.city] = acc[curr.city] ? acc[curr.city] + 1 : 1; return acc; }, {}); console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.