1

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}

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.