0

I have a (currently static) JSON blob which I am mapping over to output a list item for each object in a React application. However, I want to order the output alphabetically by a specific key.

There is already an answer for the sorting: Sort array of objects by string property value in JavaScript

function compare(a,b) {
  if (a.last_nom < b.last_nom)
    return -1;
  else if (a.last_nom > b.last_nom)
    return 1;
  else 
    return 0;
}

objs.sort(compare);

But within my React application, I am not sure how to then sort the mapped array... should I do it as part of the map function? Or separately? Do I chain the sort on after the map?

JSON:

[
    {
        "name": "Apple",
        "category": "Fruit"
    },
    {
        "name": "Pear",
        "company": "Fruit"
    },
    {
        "name": "Skittles",
        "company": "Confectionary"
    },
    {
        "name": "Milk",
        "company": "Dairy"
    },
    {
        "name": "Brie",
        "company": "Dairy"
    },
    {
        "name": "Twix",
        "company": "Confectionary"
    }
]

MAP:

return this.fetchProduce().map((item) => (
    <Item key={item.name} item={item} />
));

Thanks in advance :)

Community
  • 1
  • 1
Le Moi
  • 975
  • 2
  • 15
  • 41

0 Answers0