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

109
Views
Array.sort method not working when sorting by property

I have a basic array, that I'm trying to sort by the source property:

const arr = [
    { source: '64', target: '63' },
    { source: '61', target: '64' },
    { source: '114', target: '63' },
];

console.log('before', arr);

arr.sort(
    (a, b) => a.source > b.source
        // move element to a lower index
        ? -1
            // move element to a higher index
            : b.source > a.source
            ? 1
        : 0);
        
console.log('after', arr);

But this leaves the array untouched. What am I doing wrong here?

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

0

I think you are over complicating it.

arr.sort((a,b) => a.source - b.source);
about 4 years ago · Juan Pablo Isaza Report

0

Convert your strings in the array to numbers.

const arr = [
    { source: 64, target: 63 },
    { source: 61, target: 64 },
    { source: 114, target: 63 },
];

console.log('before', arr);

arr.sort(
    (a, b) => a.source > b.source
        // move element to a lower index
        ? -1
            // move element to a higher index
            : b.source > a.source
            ? 1
        : 0);
        
console.log('after', arr);

about 4 years ago · Juan Pablo Isaza Report

0

You need to convert strings to integers, before making comparisons, otherwise non-empty string will coerce to true and you are basically doing true > true inside your sort resolver.

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!