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?
sourceproperty as a string instead of as a number try parsinga.sourceandb.sourceto Numberarr.sort((a, b) => parseInt(a.source) - parseInt(b.source))arr.sort((a, b) => a.source-b.source);