-2
    {
    "lion":{
    "age_in_years":"10",
    "name":"king",
    "country":"africa"
    },

    "elephant":{
    "age_in_years":"15",
    "name":"hero",
    "country":"usa"
    },

    "racoon":{
    "age_in_years":"5",
    "name":"thanos",
    "country":"syria"
    },
   }

This is the data I'm getting through a web socket in react-native. I want to sort it in ascending order based on the "age_in_years". So the oldest animal's data should be shown at top and the youngest data at the last.

  • Does this answer your question? [Sorting object property by values](https://stackoverflow.com/questions/1069666/sorting-object-property-by-values) – pilchard Feb 11 '22 at 15:16
  • @lucifer DId you find any solution or resource for it ?https://stackoverflow.com/questions/70747479/trying-to-build-an-rdp-app-in-react-native-windows we are also looking for same – volvereabhi Feb 12 '22 at 12:44

3 Answers3

1

You sould better work with an array insted of object as below, first map it into array and parse the age_in_years and sort it.

const obj2Array = Object.entries(<YourObject>).map(([key, value]) => ({...value, _id: key, age_in_years: parseInt(value.age_in_years)}));
const sorted = obj2Array.sort((a, b) => a.age_in_years - b.age_in_years);

Then you can use .reduce if you want the object back, nevertheless you can use the sorted array to render it.

  • or [Object.fromEntries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries) – James Feb 11 '22 at 16:03
1

Sort by age in years oldest first

// use slice() to copy the array
    var byAge = array.slice(0);
    byAge.sort(function(a,b) {
        return a.age_in_years - b.age_in_years ;
    });
Sourav Dey
  • 1,051
  • 1
  • 13
  • 21
0

Store the values in array and make a sort function.

const numbers = [info.lion.age_in_years, info.elephant.age_in_years, info.racoon.age_in_years];

const ascNumbers = numbers.sort((a,b) =>  a-b);

If you need descending make it like this:

 const descNumbers = numbers.sort((a,b) =>  b-a);
todevmilen
  • 82
  • 1
  • 12