I create this array of objects:
const palette = [
{
color: 'Blue',
brightness: 'Soft',
},
{
color: 'Blue',
brightness: 'Medium',
},
{
color: 'Blue',
brightness: 'Principal',
},
{
color: 'Magenta',
brightness: 'Soft',
},
{
color: 'Magenta',
brightness: 'Medium',
},
{
color: 'Magenta',
brightness: 'Principal',
}
]
I want a new array with objects in this order:
const colorOrder = ['Blue', 'Magenta']
const brightnessOrder = ['Principal', 'Soft', 'Medium']
So this is the result I would like to have:
const colors = [
{
color: 'Blue',
brightness: 'Principal',
},
{
color: 'Blue',
brightness: 'Soft',
},
{
color: 'Blue',
brightness: 'Medium',
},
{
color: 'Magenta',
brightness: 'Principal',
}
{
color: 'Magenta',
brightness: 'Soft',
},
{
color: 'Magenta',
brightness: 'Medium',
},
]
I try this function:
function sortArrayByAnotherArray(array: any[], order: number[] | string[], key: string) {
const newArray = array.slice(0).sort((a, b) => {
const A = a[key]
const B = b[key]
return order.indexOf(A) < order.indexOf(B) ? 1 : -1
})
return newArray
}
I call it in this way:
const palette1 = sortArrayByAnotherArray(
palette,
brightnessOrder,
'brightness'
)
const palette2 = sortArrayByAnotherArray(
palette1,
colorOrder,
'color'
)
console.log('\n', palette)
console.log('\n', brightnessOrder)
console.log(palette1)
console.log('\n', colorOrder)
console.log(palette2)
The result is:
`
` [ { color: 'Blue', brightness: 'Soft' },
{ color: 'Blue', brightness: 'Medium' },
{ color: 'Blue', brightness: 'Principal' },
{ color: 'Magenta', brightness: 'Soft' },
{ color: 'Magenta', brightness: 'Medium' },
{ color: 'Magenta', brightness: 'Principal' } ]
`
` [ 'Principal', 'Soft', 'Medium' ]
[ { color: 'Blue', brightness: 'Medium' },
{ color: 'Magenta', brightness: 'Medium' },
{ color: 'Blue', brightness: 'Soft' },
{ color: 'Magenta', brightness: 'Soft' },
{ color: 'Blue', brightness: 'Principal' },
{ color: 'Magenta', brightness: 'Principal' } ]
`
` [ 'Blue', 'Magenta' ]
[ { color: 'Magenta', brightness: 'Medium' },
{ color: 'Magenta', brightness: 'Soft' },
{ color: 'Magenta', brightness: 'Principal' },
{ color: 'Blue', brightness: 'Medium' },
{ color: 'Blue', brightness: 'Soft' },
{ color: 'Blue', brightness: 'Principal' } ]
It's a mess, the order is not like the one in the arrays: colors are inverted and also brightness values. Then I think that call this function twice (or more) creates problems. Is there a way to solve this? Exists a smarted way to do what I need?