Reputation: 13
I have this data:
const data = [
{
name: 'chase',
advisors: [
{
name: 'mark',
clients: [
{ name: 'carol', savings: 500, checking: 600 },
{ name: 'toby', savings: 500, checking: 300 },
{ name: 'nich' }
]
},
{
name: 'holly',
clients: [
{ name: 'john', savings: 900 },
{ name: 'jim', checking: 200 },
{ name: 'bruce', checking: 200 },
{ name: 'sarah', savings: 500, checking: 300 }
]
}
]
},
{
name: 'citiBank',
advisors: [
{
name: 'cindy',
clients: [ { name: 'casey', savings: 500, checking: 200 } ]
},
{ name: 'bob', clients: null }
]
},
{ name: 'hsbc', advisors: null }
];
The output we have to get is an array of objects with that are ordered by greatest value of savings first, and if the savings value is the same, we have to order by the greatest checking value first.
Finally, the client array should look like this:
[{ name: 'john', savings: 900, firm:'chase',advisor:'holly' },{ name: 'carol', savings: 500, checking: 600, firm: 'chase', advisor: 'mark'},{ name: 'sarah', savings: 500, checking: 300 ,advisor:'holly',firm:'chase'},{ name: 'toby', savings: 500, checking: 300, firm:'chase',advisor:'mark', },{ name: 'casey', savings: 500, checking: 200,firm:'citi bank',advisor:'cindy' }....]
Below is the function defined
const maxSavingsData = ()=>{
const client = [];
console.log(client);
}
maxSavingsData(data);
Upvotes: 1
Views: 59
Reputation: 350054
I would split this task into two phases:
sort
callback function.Here is how that could work:
const maxSavingsData = (data) =>
data.flatMap(({name: firm, advisors}) =>
(advisors ?? []).flatMap(({name: advisor, clients}) =>
(clients ?? []).map(client => ({...client, firm, advisor}))
)
).sort((a, b) =>
(b.savings ?? 0) - (a.savings ?? 0) ||
(b.checking ?? 0) - (a.checking ?? 0) ||
a.name.localeCompare(b.name)
);
const data = [{name: 'chase',advisors: [{name: 'mark',clients: [{ name: 'carol', savings: 500, checking: 600 },{ name: 'toby', savings: 500, checking: 300 },{ name: 'nich' }]},{name: 'holly',clients: [{ name: 'john', savings: 900 },{ name: 'jim', checking: 200 },{ name: 'bruce', checking: 200 },{ name: 'sarah', savings: 500, checking: 300 }]}]},{name: 'citiBank',advisors: [{name: 'cindy',clients: [ { name: 'casey', savings: 500, checking: 200 } ]},{ name: 'bob', clients: null }]},{ name: 'hsbc', advisors: null }];
const clients = maxSavingsData(data);
console.log(clients);
Upvotes: 1