Move an array element from one array position to another

后端 未结 30 2968
渐次进展
渐次进展 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条回答
  •  Happy的楠姐
    2020-11-22 09:07

    I've implemented an immutable ECMAScript 6 solution based off of @Merc's answer over here:

    const moveItemInArrayFromIndexToIndex = (array, fromIndex, toIndex) => {
      if (fromIndex === toIndex) return array;
    
      const newArray = [...array];
    
      const target = newArray[fromIndex];
      const inc = toIndex < fromIndex ? -1 : 1;
    
      for (let i = fromIndex; i !== toIndex; i += inc) {
        newArray[i] = newArray[i + inc];
      }
    
      newArray[toIndex] = target;
    
      return newArray;
    };
    

    The variable names can be shortened, just used long ones so that the code can explain itself.

提交回复
热议问题