1

I want to sort items after using map() function. But the sorting must be based on a specific item's property. Then how I can customize the index before I pass it to "key"?

Here the response from the API

[
  {
    "typeId": 2,
    "count": 410
  },
  {
    "typeId": 3,
    "count": 2
  },
  {
    "typeId": 4,
    "count": 19
  },
  {
    "typeId": 5,
    "count": 21
  },
  {
    "typeId": 6,
    "count": 1
  },
  {
    "typeId": 7,
    "count": 80
  }
   ...
]

Data exploitation

 <div className="top-error-ctn">
  <span className="heading">Top Errors</span>
  <p>
    Sorted By Type
  </p>
  <div className="row">
     {Sometest ? (
       all.slice(0, 6).map((all, index) => {
          return <ErrorBar key={index} all={all} />;
       })
     ) : (
       <span>Nothing to see</span>
     )}
  </div>
</div>

Data Rendering

<div>
  <div className="side">
    <div>{all.typeId}</div>
  </div>
  <div className="middle">
    <div className="bar-container">
      <div className="bar-5"></div>
    </div>
  </div>
  <div className="side right">
    <div>{all.count}</div>
  </div>
</div>

2 Answers 2

2

You can use Array.prototype.sort() function like below.

const items = [
  {
    "typeId": 2,
    "count": 410
  },
  {
    "typeId": 3,
    "count": 2
  },
  {
    "typeId": 4,
    "count": 19
  },
  {
    "typeId": 5,
    "count": 21
  },
  {
    "typeId": 6,
    "count": 1
  },
  {
    "typeId": 7,
    "count": 80
  }
];
console.log('Sort by typeId:', items.sort((a, b) => a.typeId - b.typeId));

console.log('Sort by count:', items.sort((a, b) => a.count - b.count));

Sign up to request clarification or add additional context in comments.

Comments

1

You can sort like this

all.sort(function(a, b) {
    return b.count- a.count;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.