I have an object that looks like the example below. I want the object that is equal to the id in the variable to be sorted first. How can I do that?
const id = 15;
const obje = [
{
"name": "Join",
"phone": "1234",
"email": "test@mysite.com",
"id": "12"
},
{
"name": "Join2",
"phone": "4321",
"email": "test2@mysite.com",
"id": "15"
}
]
What I want to do is to rank the object equal to the id in the variable to the top.
Thanks for your help in advance 🙏🏻
Instead of sorting find the index of the object where its id matches the search id, then splice it out, and then add it to the start of the array with unshift. You are mutating the array but it's quick, and without knowing the complete structure of your array, probably the easiest approach.
const id=15,arr=[{name:"Join",phone:"1234",email:"test@mysite.com",id:"12"},{name:"Join2",phone:"4321",email:"test2@mysite.com",id:"15"}];
const index = arr.findIndex(obj => obj.id === id);
arr.unshift(arr.splice(index, 1)[0]);
console.log(arr);