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= [\"ema
If you don't want to alter the existing array, you can use ES6 destructuring with the filter method to create a new copy while maintaining the order of the other items.
const data = ["email", "role", "type", "name"];
const newData = ['role', ...data.filter(item => item !== 'role')];
To check whether an item exists in an array you should to use .includes()
instead of in
(as already noted here, in
is for properties in objects).
This function does what you are looking for: (removes the item from the position it is in and reads in front)
data = ["email","role","type","name"];
moveToFirst("role", data)
function moveToFirst(s, r){
if (r.includes(s)){
r.splice(r.indexOf(s),1);
r.unshift(s);
}
}
console.log(data)
in
operator is about properties, not about items in arrays. See How do I check if an array includes an object in JavaScript? for what to use else..remove()
function you're using does take an index of an item.Similar to @Tandroid's answer but a more general solution:
const putItemsFirst = ({ findFunction, array }) => [
...array.filter(findFunction),
...array.filter(signer => !findFunction(signer)),
];
Can be used like this
putItemsFirst({
array: ["email","role","type","name"],
findFunction: item => item === 'role',
})
Something similar to this is what I ended up using,
var data= ["email","role","type","name"];
if ("role" in data) data.splice(data.indexOf("role"),1); data.unshift("role");
data;
let data = [0, 1, 2, 3, 4, 5];
let index = 3;
data.unshift(data.splice(index, 1)[0]);
// data = [3, 0, 1, 2, 4, 5]