Move an array element from one array position to another

后端 未结 30 2535
渐次进展
渐次进展 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条回答
  •  -上瘾入骨i
    2020-11-22 09:08

    Immutable version without array copy:

    const moveInArray = (arr, fromIndex, toIndex) => {
      if (toIndex === fromIndex || toIndex >= arr.length) return arr;
    
      const toMove = arr[fromIndex];
      const movedForward = fromIndex < toIndex;
    
      return arr.reduce((res, next, index) => {
        if (index === fromIndex) return res;
        if (index === toIndex) return res.concat(
          movedForward ? [next, toMove] : [toMove, next]
        );
    
        return res.concat(next);
      }, []);
    };
    

提交回复
热议问题