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

138
Views
JS Array Sorting Using Expression

Is there a way to bring the related object to the first index of the array using sort function?

Here is what I tried using sort only

const arr = [{
    id: 'a',
    name: 'test name 1'
  },
  {
    id: 'b',
    name: 'test name 2'
  },
  {
    id: 'c',
    name: 'test name 3'
  }
];

const testId = 'c';


const sortedArr = arr.sort((a, b) => a.id === testId || b.id === testId ? 1 : -1);

console.log(sortedArr); // logs b, a, c but the expected result is c, a, b

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The issue here is because everytime that a OR b are the testId, it will be "bumped". So, if you check only to one value it works.

Here an example :

const arr = [
  {
    id: 'c'
  },
  {
    id: 'a'
  },
  {
    id: 'b'
  }
];

function checkFor(myList, testId) {
    console.log('Checking for ' + testId);
    const sortedArr = arr.sort((a, b) => b.id === testId ? 1 : -1);

    console.log(sortedArr);
}

checkFor(arr, 'c');
checkFor(arr, 'b');

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!