How to change the position of an array element?

后端 未结 7 813
Happy的楠姐
Happy的楠姐 2020-12-24 06:45

I have a question on how I can change the index of a array element, so that it doesn\'t come at the 7. position but at position 2 instead...

Is there a function to h

7条回答
  •  半阙折子戏
    2020-12-24 06:54

    The answers here don't cover both possible scenarios. While the question dealt with an origin index higher than the destination, if the reverse is true then the solution below won't work:

    array.insert 7, array.delete_at(2)
    

    This is because deleting the value at 2 shifts everything (above 2) down the array by 1. Now our destination index of 7 is pointing at what used to be at index 8.

    To fix this, we need to check if the origin is less than the destination and if so, deduct 1 from the destination.

    origin = 2
    destination = 7
    
    destination -= 1 if origin < destination
    array.insert destination, array.delete_at(origin)
    

提交回复
热议问题