Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array from an object?

Tags:

javascript

How to sort an array from an object ? The code :

         let A = [ { text: '故事', value: 'story', },
                   { text: '诗歌', value: 'poetry', },
                   { text: '励志', value: 'inspirational', }
                 ];
         // array B from backend** 
         let B = { 
                   story: 2,
                   poetry: 34,
                   inspirational: 30,
                 };

I want to get this :

             [ 
               { text: '诗歌', value: 'poetry', },
               { text: '励志', value: 'inspirational'},
               { text: '故事', value: 'story', }, 
             ];
like image 982
蒋建雨 Avatar asked May 20 '26 08:05

蒋建雨


2 Answers

Simply you can use JavaScript sort function.

Note: When sorting numbers, you can simply use the compact comparison:

Compact Comparison:: myArray.sort((n1,n2) => n1 - n2);

let A = [ { text: '故事', value: 'story', },
                   { text: '诗歌', value: 'poetry', },
                   { text: '励志', value: 'inspirational', }
                 ];
         // array B from backend** 
         let B = { 
                   story: 2,
                   poetry: 34,
                   inspirational: 30,
                 };
 A.sort((a, b) => B[b.value]-B[a.value] );
                 console.log(A);
like image 196
NullPointer Avatar answered May 22 '26 21:05

NullPointer


You can use an arrow function in array.sort as a custom comparator. Sorting in reverse order is accomplished by indexing into the B object to retrieve the sort value for compared elements and subtracting a's value from b.

let A = [ 
  { text: '故事', value: 'story', },
  { text: '诗歌', value: 'poetry', },
  { text: '励志', value: 'inspirational', }
];
let B = { 
  story: 2,
  poetry: 34,
  inspirational: 30,
};

const sorted = A.sort((a, b) => B[b.value] - B[a.value]);

console.log(sorted);
like image 24
ggorlen Avatar answered May 22 '26 20:05

ggorlen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!