Categories
Mastering Development

How do you sort/order a map function using .sort or lodash?

I have been trying to sort a map function with no results. I tried a few different methods but have not been able to sort by the section.tid. Is there a way to orderby a nested tid?

Code:

{data.policies.data.map((policy, i) => (
  <div key={i}>
    <div>
      {policy.policy_sections
        .sort(({ tid: previousTID }, { tid: currentTID }) => previousTID - currentTID)
        .map((section, i) => (
        <div key={i}>
          {!arr.includes(section.name) && arr.push(section.name) && (
            <Link
              href={`/section/${section.tid}`}
              as={`/section/${section.tid}/`}
              >
              <a>
                {section.tid} - {section.name}
              </a>
            </Link>
          )}
        </div>
      ))}
    </div>
  </div>
))}

Pretty sure .sort(({ tid: previousTID }, { tid: currentTID }) => previousTID - currentTID) is not doing anything

Query:

{
  policies {
    data {
      policy_number
      policy_sections {
        tid
        name
        slug
      }
    }
  }
}

Data (Example):

{
  "data": {
    "policies": {
      "data": [
        {
          "policy_number": "XXXXXX",
          "policy_sections": [
            {
              "tid": "2237",
              "name": "XXXXXX",
              "slug": "XXXXXX"
            }
          ]
        },
        {
          "policy_number": "XXXXXX",
          "policy_sections": [
            {
              "tid": "2237",
              "name": "XXXXXX",
              "slug": "XXXXXX"
            }
          ]
        },

   ...

Leave a Reply

Your email address will not be published. Required fields are marked *