Move an array element from one array position to another

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

    This version isn't ideal for all purposes, and not everyone likes comma expressions, but here's a one-liner that's a pure expression, creating a fresh copy:

    const move = (from, to, ...a) => (a.splice(to, 0, ...a.splice(from, 1)), a)
    

    A slightly performance-improved version returns the input array if no move is needed, it's still OK for immutable use, as the array won't change, and it's still a pure expression:

    const move = (from, to, ...a) => 
        from === to 
        ? a 
        : (a.splice(to, 0, ...a.splice(from, 1)), a)
    

    The invocation of either is

    const shuffled = move(fromIndex, toIndex, ...list)
    

    i.e. it relies on spreading to generate a fresh copy. Using a fixed arity 3 move would jeopardize either the single expression property, or the non-destructive nature, or the performance benefit of splice. Again, it's more of an example that meets some criteria than a suggestion for production use.

提交回复
热议问题