Move an array element from one array position to another

后端 未结 30 2538
渐次进展
渐次进展 2020-11-22 08:36

I\'m having a hard time figuring out how to move an array element. For example, given the following:

var arr = [ \'a\', \'b\', \'c\', \'d\', \'e\'];
<         


        
30条回答
  •  攒了一身酷
    2020-11-22 08:58

    As an addition to Reid's excellent answer (and because I cannot comment); You can use modulo to make both negative indices and too large indices "roll over":

    function array_move(arr, old_index, new_index) {
      new_index =((new_index % arr.length) + arr.length) % arr.length;
      arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
      return arr; // for testing
    }
    
    // returns [2, 1, 3]
    console.log(array_move([1, 2, 3], 0, 1)); 

提交回复
热议问题