I am facing issues with the compare function in sort in Javascript.
This is the sort function-
const sortBy = ( key ) => {
return ( a, b ) => {
if ( a[ key ] > b[ key ] ) {
return 1;
} else if ( b[ key ] > a[ key ] ) {
return -1;
}
return 0;
};
};
This function is called here-
function formatrules( data ) {
/*The native sort modifies the array in place, so we use `.concat()`
to copy the array, then sort.*/
return data
.concat()
.sort( sortBy( 'to.name' ) )
.map( ( rule ) => {
......
} );
}
The data object looks like this -
data: (3) [{...}, {...}, {...}]
0:{from:{...}, to: {...}}
>from:{val: '#0056da'}
>to: {val: '000000', name: 'black'}
Issue: The a[key] in the sortBy function doesn't resolve to a value as key = 'to.name'. If I hard code the value as a.to.name then it works fine. How should I change the value of key so it works?
I am using the square notation as shared in this thread but it doesn't work.