0

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.

2
  • 2
    If both arguments to < are strings, it compares lexicographically; "10P" is before "2" just like "aardvark" is before "b". parseInt if you want numeric comparison. Commented Feb 13, 2018 at 4:09
  • 1
    Note that this is an array of objects, not a multidimensional array. Commented Feb 13, 2018 at 4:25

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Minor: Using the unary operator +, i.e +'123' will also parse a String to a whole Number
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.