I recently had a training task:
given the array of {"color":string,"size":int}
Objects, print them sorted by size. If multiple objects share same size, they,among themselves, should be sorted by color alphabetically.
I have written this:
//example:
let x = [{"color":"green" ,"size":42},{"color":"blue" ,"size":42},{"color":"red" ,"size":42},{"color":"blue" ,"size":41}];
//1st - sorting by size:
x=x.sort((a,b)=>a.size-b.size)
//2nd - find unique sizes.
const uniqueSizes = [...new Set(x.map(item => item.size))];
//3rd - group the initial array into individual arrays of same size
let grouped=[]
for (const size of uniqueSizes){
let found=x.filter((f)=>f.size===size);
grouped.push(found)
}
console.log(grouped)
//last - sort individual groups and print them.
for (const g of grouped){
console.log(
g.sort((a,b)=>a.color.localeCompare(b.color)).map(z=>`${z.size} ${z.color}`).join(`n`)
)
}
Here is the result:
41 blue
42 blue
42 green
42 red
Question:
Is there an easier/more elegant way to do this? I think , solution is cumbersome and creates a lot of unnecessary variables + i think that step by step approach is also time consuming;