1

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.

Sonam
  • 11
  • 1
  • obj['to.name'] is not equal to obj['to']['name'] , i created an example for you [link](https://jsfiddle.net/309mLbxg/3/) – tknkrtl Mar 24 '23 at 08:51
  • 1
    Thank you. Your link helped me understand my mistake in accessing the object value. – Sonam Mar 24 '23 at 11:20
  • Glad it helped! You can thumbs up my comment for people who will have similar problems in the future. – tknkrtl Mar 24 '23 at 12:15

0 Answers0