Move an array element from one array position to another

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

    Another pure JS variant using ES6 array spread operator with no mutation

    const reorder = (array, sourceIndex, destinationIndex) => {
    	const smallerIndex = Math.min(sourceIndex, destinationIndex);
    	const largerIndex = Math.max(sourceIndex, destinationIndex);
    
    	return [
    		...array.slice(0, smallerIndex),
    		...(sourceIndex < destinationIndex
    			? array.slice(smallerIndex + 1, largerIndex + 1)
    			: []),
    		array[sourceIndex],
    		...(sourceIndex > destinationIndex
    			? array.slice(smallerIndex, largerIndex)
    			: []),
    		...array.slice(largerIndex + 1),
    	];
    }
    
    // returns ['a', 'c', 'd', 'e', 'b', 'f']
    console.log(reorder(['a', 'b', 'c', 'd', 'e', 'f'], 1, 4))
          
     

提交回复
热议问题