Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
First show the object that is equal to the incoming variable

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 ๐Ÿ™๐Ÿป

about 4 years ago ยท Juan Pablo Isaza
1 answers
Answer question

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);

about 4 years ago ยท Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!