-2

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

VLAZ
  • 26,331
  • 9
  • 49
  • 67
meridyen
  • 3
  • 3
  • Does this answer your question? [Sort array of objects by string property value](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value). What have you tried already? – WOUNDEDStevenJones May 31 '22 at 20:54

1 Answers1

0

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);
Andy
  • 61,948
  • 13
  • 68
  • 95
  • Why does it add square brackets to the object it moves up? – meridyen Jun 01 '22 at 09:38
  • @meridyen, sorry that was an error on my part. `splice` returns an array. You just need to take the first element from that. I've fixed the code in the answer. – Andy Jun 01 '22 at 12:57