Reputation: 48
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
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
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
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