Reputation: 63
I seem to be having a little issue getting an array of objects to sort properly.
For example, let's say I have the following:
var items = [
{id: '1', itn: '1'},
{id: '2', itn: '10P'},
{id: '3', itn: '2'},
{id: '4', itn: '3'}
];
I need to sort this array based on the value in "itn." However, when I run the function below I get it listed as 1, 10P, 2, 3 instead of 1, 2, 3, 10P.
userData.sort(function (a, b) {
return (b.itn > a.itn) ? -1 : (b.itn < a.itn) ? 1 : 0;
});
I'm a bit stuck in how to go forward with this and am also unsure what kind of keywords to search for to get the correct guidance. Any help is appreciated!
Thanks in advance.
Upvotes: 0
Views: 64
Reputation: 22524
You can use string#localeCompare
with numeric
property as true
.
var items = [{id: '1', itn: '1'},{id: '1', itn: '10P'},{id: '1', itn: '2'},{id: '1', itn: '3'}];
items.sort((a,b) => a.itn.localeCompare(b.itn, undefined, {numeric: true}));
console.log(items);
Upvotes: 0
Reputation: 68933
It seems that you are trying to sort the array based on the integer part present in itn
. To achieve that you can use parseInt()
to convert the item (itn
) to integer then compare those integer values:
var userData = [
{id: '1', itn: '1'},
{id: '1', itn: '10P'},
{id: '1', itn: '2'},
{id: '1', itn: '3'}
];
var res = userData.sort(function (a, b) {
a = parseInt(a.itn);
b = parseInt(b.itn);
return (b > a) ? -1 : (b < a) ? 1 : 0;
});
console.log(res)
Upvotes: 2