Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript move an item of an array to the front

I want to check if an array contains "role". If it does, I want to move the "role" to the front of the array.

var data= ["email","role","type","name"]; if ("role" in data) data.remove(data.indexOf("role")); data.unshift("role") data; 

Here, I got the result:

["role", "email", "role", "type", "name"]

How can I fix this?

like image 666
user2634156 Avatar asked May 28 '14 20:05

user2634156


People also ask

How do you move an object to the front of an array?

📚 The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. 📚 The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

How do I move an element to an array first?

To move element to first position in array with JavaScript, we can use the spread operator and the array slice method. We call data. slice to get the last element and the first 3 elements respectively. Then we spread each array into a new array to populate the values of the returned arrays in the new array.

How do you move position of element in array?

To change the position of an element in an array:Use the splice() method to insert the element at the new index in the array. The splice method changes the original array by removing or replacing existing elements, or adding new elements at a specific index.

How do you move the last element in an array to the first in JavaScript?

Now, if you need to move the last item to the first position, just use the return function array. pop() as input to the function array. unshift().


2 Answers

You can sort the array and specify that the value "role" comes before all other values, and that all other values are equal:

var first = "role"; data.sort(function(x,y){ return x == first ? -1 : y == first ? 1 : 0; }); 

Demo: http://jsfiddle.net/Guffa/7ST24/

like image 144
Guffa Avatar answered Oct 21 '22 14:10

Guffa


The cleanest solution in ES6 in my opinion:

let data = ["email","role","type","name"]; data = data.filter(item => item !== "role"); data.unshift("role"); 
like image 45
Skylar Brown Avatar answered Oct 21 '22 13:10

Skylar Brown