Loo Gie
Loo Gie

Reputation: 48

Sort an array by object field

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

Upvotes: 0

Views: 64

Answers (3)

Spectric
Spectric

Reputation: 31987

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

Upvotes: 1

AlexSp3
AlexSp3

Reputation: 2293

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

Upvotes: 1

Martes Carry
Martes Carry

Reputation: 41

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

Upvotes: 1

Related Questions