Move an array element from one array position to another

后端 未结 30 3173
渐次进展
渐次进展 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:48

    let ar = ['a', 'b', 'c', 'd'];
    
    function change( old_array, old_index , new_index ){
    
      return old_array.map(( item , index, array )=>{
        if( index === old_index ) return array[ new_index ];
        else if( index === new_index ) return array[ old_index ];
        else return item;
      });
    
    }
    
    let result = change( ar, 0, 1 );
    
    console.log( result );
    

    result:

    ["b", "a", "c", "d"]
    

提交回复
热议问题