1

I am fetching an array of objects from the server and I use "map" to render the array elements as following :

data.map((item, index) => {
     <div>{item.index + 1}</div>
     <div>{item.name}</div>
     <div>{item.price}</div>
})

and I get a list of items starting from index 1 in ascending order. What I want to do is, I want to rearrange the array in a descending order instead. I want the first element rendered with the latest index that indicates the last element of the array. Is there a way to achieve this in javascript and ReactJs. Thanks in advance.

1
  • 2
    Could you post an example of the output you want versus the output you have now? Commented Aug 13, 2020 at 10:52

3 Answers 3

1

You can easily do this by issueing the reverse method:

data.reverse().map((item, index) => {
     <div>{item.index + 1}</div>
     <div>{item.name}</div>
     <div>{item.price}</div>
})

Do keep in mind that this also changes the original array. So the reverse method will not only return a reversed array of data, but also mutate the data array itself.

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

3 Comments

I want the first element rendered with the latest index that indicates the last element of the array
Hmmm maybe I am misunderstanding the question. I will ask the OP to post an example of the output he wants.
That worked perfectly as expected. I just fixed the index to start from the length of the array. Thanks a lot for help.
0

Something like this?

data.map((item, index) => {
     <div>{data.length - item.index}</div>
     <div>{item.name}</div>
     <div>{item.price}</div>
})

is the item.index intentional here? or did you mean just index?

Comments

0

What I have understood is that you want to sort this in descending order of 'index' that is present as a key in every object. If that is the case, this will work.

data
  .sort((a,b)=>{return b.index-a.index}) // sorting it in descending order
  .map((item, index) => {
     <div>{item.index + 1}</div>
     <div>{item.name}</div>
     <div>{item.price}</div>
})

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.