Good day, turned up such a task to move the element of the array to the beginning. It seems to have done, but can there be a more beautiful way to move an element to the beginning?

var arr = [0, 1, 2, 3, 4, 5]; console.log(arr); var removed = arr.splice(3, 1); arr.unshift(removed[0]); console.log(arr); 

  • What do you call beautiful? In short? More versatile? - LEQADA
  • Beautiful = shorter. Maybe there is some kind of ready-made special method for moving along the key to the beginning. - Puvvl
  • @Puvvl How do you like this option arr.unshift (... arr.splice (3,1)); ? - Alexander
  • @ Alexander thought about that) This option is generally perfect. Thank you!) - Puvvl

3 answers 3

Suitable if the item is more than 1

 var arr = [0, 1, 2, 3, 4, 5] arr.unshift(...arr.splice(3,1)); console.log(arr); 

    You can sort the array by specifying that the desired value should be first of all.

     var arr = [0, 1, 2, 3, 4, 5]; var value = 3; arr.sort(function(x,y){ return x == value ? -1 : y == value ? 1 : 0; }); console.log(arr); 

    You can cut an element from an array. You need an element and shove it at the beginning using 2 splice

     var arr = [0, 1, 2, 3, 4, 5]; var index = 3; arr.splice(0, 0, arr.splice(index, 1)[0]); console.log(arr); 

    • Good approach, but I would like to be even shorter :) - Puvvl
    • one
      The standard does not guarantee that Array.sort () is a stable sort. Accordingly, depending on the JS interpreter used, it may turn out that other elements will also be swapped. - Yaant
    • It was quite an option with splice . With sort something incomprehensible is happening to me, it adds time, but thanks!) - Puvvl

     var a = [0, 1, 2, 3, 4, 5]; console.log(a); var b = [a[3]].concat(a.slice(0, 3), a.slice(4)) console.log(b); 
     .as-console-wrapper.as-console-wrapper { max-height: 100vh } 

    • You have duplicated the element in the array - Puvvl
    • @Puvvl, oh .. corrected. - Qwertiy