I have an array of objects that looks like this :
let obj = [
{ name: 'John',
company: {name: 'Wilsons'}
},
{ name: 'Jim',
company: {name: 'Allisons'}
},
{ name: 'George',
company: {name: 'Filberts'}
},
]
Ideally, I can sort this dynamically, by running
const sortMe = val => {
obj.sort((a, b) => a[val] > b.[val])
}
sortMe(company.name) =
[
{ name: 'Jim',
company: {name: 'Allisons'}
},
{ name: 'George',
company: {name: 'Filberts'}
},
{ name: 'John',
company: {name: 'Wilsons'}
},
]
sortMe(name)
=> sorted by name...
But it won't work. I also tried splitting the value with a conditional
if (val.includes('.')) {
let categories = val.split('.')
[...obj].sort((a, b) => {
if (a[categories[0]][categories[1]] <
b[categories[0]][categories[1]]) {
return -1;
} if (a[categories[0]][categories[1]] >
b[categories[0]][categories[1]]) {
return 1;
}
return 0;
})
}
which would essentially give me company and name as separate values and I could target it that way. But it did not work.