i have array and i want to rearrange some element of that array like i want 2nd element should be in 0th position and 3rd element should be in 2nd position. look screenshot for reference and final result should be like this -> Quicky Starts | Guilds | Reference Docs | Help
and if i add any new item to array then it should appear at last position
<Nav className="me-auto">
{newNavArr.map((button, index) => (
<NavLink
key={index}
to={button.slug}
position="relative"
padding="20px"
>
{button.title}
</NavLink>
))}
</Nav>
3
Answers
I think you can do this, first you need to create a list of sorted arrays, if your data is coming dynamically then you can sort the data in a new array according to your array as you can see below code, I hope this would be helpful.
This is the algorithm to change any position of an array write the element name you want to change and write second element name you want to swap with.
Code:
If you want to change the 2nd element should be the 1st position do this again.
Is far way more optimal to make this position-ordering with CSS applying a flexbox (
display: flex
) +order
rule. It’s worth noting that the other solutions suggested rely on different mapping methods (such assplice
,includes
, andforEach
) that create a new instance of the array (which is later cleaned up by the garbage collector but it’s not optimal at all)And the CSS:
You can add your custom order as desired to the rest of the elements