Move an array element from one array position to another

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

    This method will preserve the original array, and check for bounding errors.

    const move = (from, to, arr) => {
        to = Math.max(to,0)
        from > to 
            ? [].concat(
                arr.slice(0,to), 
                arr[from], 
                arr.filter((x,i) => i != from).slice(to)) 
            : to > from
                ? [].concat(
                    arr.slice(0, from), 
                    arr.slice(from + 1, to + 1), 
                    arr[from], 
                    arr.slice(to + 1))
                : arr}
    

提交回复
热议问题