0

I have an array of objects

const myarray = [ { name: 'Alex', job: 'Doctor' }, { name: 'John', job: 'Taxi Driver' }, { name: 'Marc', job: 'Taxi Driver' }, ]

How can i, for each job, print the name of the job, then all the corresponding objects ?

For example I want to be able to display:

Doctor: Alex

Taxi driver: John, Marc

2
  • What does sorting have to do with this? What have you attempted. It is a simple loop and reading the properties of the object and outputting it in some way. Commented Jul 9, 2021 at 19:32
  • @epascarello I am sorry, my english is not very good i didn't know what other word i could use to explain the problem that's why i wrote and example of what i am trying to achieve. Your comment was not of much help but thank you anyway Commented Jul 10, 2021 at 1:41

3 Answers 3

1

You can try something like this:

const myarray = [ { name: 'Alex', job: 'Doctor' }, { name: 'John', job: 'Taxi Driver' }, { name: 'Marc', job: 'Taxi Driver' } ]
const sorted = {}
myarray.forEach((e)=>{
  if(e.job in sorted){
    sorted[e.job].push(e.name);
  }else{
    sorted[e.job] = [e.name]
  }
})
console.log(sorted);

To print them in the format you want:

const myarray = [ { name: 'Alex', job: 'Doctor' }, { name: 'John', job: 'Taxi Driver' }, { name: 'Marc', job: 'Taxi Driver' } ]
const sorted = {}
myarray.forEach((e)=>{
  if(e.job in sorted){
    sorted[e.job].push(e.name);
  }else{
    sorted[e.job] = [e.name]
  }
})
for(const key in sorted){
  var str = key+': ';
  sorted[key].forEach(e=>str+=e+', ');
  console.log(str.slice(0, -2));
}

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

2 Comments

Thank you ! That's exactly what i needed. Thanks for your help
@LooGie No problem. Glad to help :)
1

first of all create object which will store job like obj = {"Taxi driver": [],"Doctor": [] } and after you can pass array myarray.forEach(e => obj[e.job].append(e.name)) after just manipulate with object. Best regards

Comments

1

It returns an object with the result you want

const myarray = [ { name: 'Alex', job: 'Doctor' }, { name: 'John', job: 'Taxi Driver' }, { name: 'Marc', job: 'Taxi Driver' }, ]

function getJobs() {
  let result = {};
  myarray.forEach(function t(e) {
    if (!result.hasOwnProperty(e.job))  result[e.job] = [];
    result[e.job].push(e.name);
  });
  return result;
}

console.log(getJobs());

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.