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?
I think you are over complicating it.
arr.sort((a,b) => a.source - b.source);
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);
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.