Reputation: 99
I want to sort an array in ascending order based on two properties.
I have following data array which looks like
[
{
id: 1,
name: 'ABP',
code: 1460,
subCode: '0010'
},
{
id: 2,
name: 'GKY',
code: 1460,
subCode: '0030'
},
{
id: 3,
name: 'CPT',
code: 1410,
subCode: '0070'
},
{
id: 4,
name: 'KLB',
code: 1470,
subCode: '0050'
},
{
id: 5,
name: 'POL',
code: 1430,
subCode: '0050'
},
{
id: 6,
name: 'FVB',
code: 1410,
subCode: '0050'
},
]
I want to sort it like
[
{
id: 6,
name: 'FVB',
code: 1410,
subCode: '0050'
},
{
id: 3,
name: 'CPT',
code: 1410,
subCode: '0070'
},
{
id: 5,
name: 'POL',
code: 1430,
subCode: '0050'
},
{
id: 1,
name: 'ABP',
code: 1460,
subCode: '0010'
},
{
id: 2,
name: 'GKY',
code: 1460,
subCode: '0030'
},
{
id: 4,
name: 'KLB',
code: 1470,
subCode: '0050'
},
]
I want to sort the array in ascending order based on code
property and if same code
exist for multiple items then I want to sort it based on subCode
of the code
property.
Problem I am facing here is, subCode
is in string and code
is in number.
I have tried using array.sort
and also by parsing subCode
in integer but it has returned me different number which I didn't understand.
Upvotes: 0
Views: 82
Reputation: 863
When you want to compare string value as number value (here is subCode
), you will need to compare them by converting to number first
See below code.
Ary.sort(function (obj1, obj2) {
if (obj1.code === obj2.code) {
return Number(obj1.subCode) - Number(obj2.subCode)
} else {
return obj1.code - obj2.code
}
})
I assume value of code
will always be number.
Upvotes: 0
Reputation: 35222
You could subtract the the code properties inside the compareFunction. If both a
and b
have the same code
property, then the ||
operator will subtract the subCode
property. The -
operator will coerce the strings to numbers and it will return a numeric value.
const input=[{id:1,name:"ABP",code:1460,subCode:"0010"},{id:2,name:"GKY",code:1460,subCode:"0030"},{id:3,name:"CPT",code:1410,subCode:"0070"},{id:4,name:"KLB",code:1470,subCode:"0050"},{id:5,name:"POL",code:1430,subCode:"0050"},{id:6,name:"FVB",code:1410,subCode:"0050"},];
input.sort((a, b) => a.code - b.code || a.subCode - b.subCode)
console.log(input)
Upvotes: 3