Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

arrays - Sorting graphQL data in JavaScript

Very much appreciated for reading this one! It might seem like easy for you, but I am quite new, so bear with me. I have a query in GraphQL which gives me the following results:

  "data": {
"completeglobaldata": [
      {
        "increasehotdays": 43,
        "countryname": "Afghanistan"
      },
      {
        "increasehotdays": 66.1,
        "countryname": "Angola"
      },
      {
        "increasehotdays": 0,
        "countryname": "Anguilla"
      },
      {
        "increasehotdays": 0,
        "countryname": "?land Islands"
      },
      {
        "increasehotdays": 51.9,
        "countryname": "Albania"
      },
]
}

Yet, now I want to sort the data in a descending way with JavaScript sort. The problem is that GraphQL will return objects and I do not understand how this would work.. I have been stuck on the array/sort page for some good hours now.

export const sortDescendingHotDays = (completeglobaldata) => {
  const countryTemperatures = completeglobaldata.map((country) => ({
    ...completeglobaldata,
  }));

  return completeglobaldata.sort((a, b) =>
    a.country.increasehotdays < b.country.increasehotdays ? 1 : -1
  );
};


This is obviously wrong, but it shows how lost I am. Oh, I am using React by the way. Ofcourse I could easily change the graphQL query to :

query MyQuery {
  completeglobaldata(order_by: {increasehotdays: desc}) {
    increasehotdays
    countryname
  }
}

But this is not possible in my situation.I really need to get the data and then sort it using Javascript sort

Thank you for your help :)

question from:https://stackoverflow.com/questions/65923461/sorting-graphql-data-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You were close! There isn’t a country key on your individual objects, and when you’re using sort, you’re already comparing two different country objects.

completeglobaldata.sort((a,b) => b.increasehotdays - a.increasehotdays)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...