Move element to first position in array
Since you are just moving one item to the top, I will just use splice()
and unshift()
the item:
var data = [
{ id: "fmgbwe45", age: 24, gender: "male" },
{ id: "kjregh23", age: 27, gender: "female" },
{ id: "kjfdhg87", age: 30, gender: "male" },
{ id: "lsdjfk43", age: 10, gender: "female" },
]
data.forEach(function(item,i){
if(item.id === "kjfdhg87"){
data.splice(i, 1);
data.unshift(item);
}
});
console.log(data);
You can use unshift
method.
var data = [
{ id: "fmgbwe45", age: 24, gender: "male" },
{ id: "kjregh23", age: 27, gender: "female" },
{ id: "kjfdhg87", age: 30, gender: "male" },
{ id: "lsdjfk43", age: 10, gender: "female" },
]
var stringToFilter = 'kjfdhg87'; //this holds 'kjfdhg87'
data.unshift(data.splice(data.findIndex(item => item.id === stringToFilter), 1)[0])
console.log(data);