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?
📚 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.
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.
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.
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().
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/
The cleanest solution in ES6 in my opinion:
let data = ["email","role","type","name"]; data = data.filter(item => item !== "role"); data.unshift("role");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With