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?
CodePudding user response:
Simple way of doing this
You can do it directly without condition inside sort
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); // ascending
//arr.sort((a, b) => b.source - a.source); // descending
console.log('after', arr);
Way of doing this by conversion
Or you can convert string to number, without extra conditions inside your sort
const arr = [{
source: '64',
target: '63'
},
{
source: '61',
target: '64'
},
{
source: '114',
target: '63'
},
];
console.log('before', arr);
arr.sort((a, b) => Number(a.source) > Number(b.source) ? -1 : 1);
console.log('after', arr);
CodePudding user response:
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.
CodePudding user response:
You need to either use numbers for the source
value or coerce them to numbers, as below:
const arr = [
{ source: '64', target: '63' },
{ source: '61', target: '64' },
{ source: '114', target: '63' },
];
console.log('before', arr);
arr.sort(
(a, b) => Number(a.source) > Number(b.source)
// move element to a lower index
? -1
// move element to a higher index
: Number(b.source) > Number(a.source)
? 1
: 0);
console.log('after', arr);
CodePudding user response:
I think you are over complicating it.
arr.sort((a,b) => a.source - b.source);
CodePudding user response:
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);
CodePudding user response:
Your sorting works.
You sort the array by string and descending
'64'
'61'
'114'
and because of having this sorting in your data, nothings happens.
For sorting the values ascending as strings swap 1
and -1
.
To get a result of numerical order convert either the values to number or use an implicit conversion by using a numerical operator, like -
.
(a, b) => a.source - b.source // ascending
(a, b) => b.source - a.source // descending