# Sorting Arrays (Comparator Function)

Hello All,
Why are these two codes giving different outputs when using the comparator function? Is it based on the unicode value of the first letters(‘N’ and ‘J’)or the length of the string(amount of characters)?

const numeric = [
{id:1, name: “Node.js”},
{id:2, name: “Javascript”}
];

• Mosh Method:
numeric.sort(function(a,b) {
if(a.name < b.name) return -1;
if(a.name > b.name) return 1;
return 0;
});
console.log(numeric);
//Output:
1: {id: 2, name: “Javascript”}
0: {id: 1, name: “Node.js”}

• Other Method:
const sortedObj = function(a,b) {
return a.name - b.name;
}
console.log(numeric.sort(sortedObj));
//Output:
0: {id: 1, name: “Node.js”}
1: {id: 2, name: “Javascript”}

Hi,

https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html

The explanation of the first link is clear, and about the ascii table : the decimal number of each character is different so if you’re getting different result it’s because of the decimal number and the condition you have set in your code.

Hi thank you for the attachments. But I still need clarification on the how/why the second code is executed.

I understand Mosh’s method and how comparator function is applied, and that the result is ascending(least => greatest); based on the ASCII Table you linked ‘N’ = 78 and ‘J’ = 74 so:

• function(a,b){ return 78 - 74}

• // 78 - 74 = 4(positive value) so a>b returns 1 meaning b comes ahead of a

However, the second code should give the same result,

Yes you’re right, i tried everything with your code but nothing worked.
But i think the reason your code isn’t working is because sorting strings is different from numbers, and as document mentioned :

To compare numbers instead of strings, the compare function can simply subtract `b` from `a`

```````function compareNumbers(a, b) {

return a - b;

}
``````

and if you look at the code above which is from document you’ll notice that it sorted numbers(values) differently from strings(names).

I tried this and it worked :

``````    `const numeric = [

{ id: 1, name: "Nodejs" },

{ id: 2, name: "Javascript" }

];

const sortedObj = function (a, b) {

if (a.name < b.name) return -1;

if (a.name > b.name) return 1;

return 0;

}

console.log(numeric.sort(sortedObj));

//OUtPUT:
1. 0: {id: 2, name: "Javascript"}
2. 1: {id: 1, name: "Nodejs"}
3. length: 2
4. __proto__: Array(0)

``````

But i’m not completely sure if that is the only reason.

The second method doesn’t work because subtracting a string from another doesn’t give a sensible numeric result. How much is “Node.js” minus “Javascript”? It’s `NaN` .