Reputation: 421
I am attempting to sort an array of objects by a name property that exists on each object. When using the sort()
method with the code below I am getting the following error:
ERROR ReferenceError: b is not defined
Here is my code:
myArray.sort( (a, b) => {
return (typeof a.name: string === 'string') - (typeof b.name === 'string')|| a.name - b.name || a.name.localeCompare(b.name)};
Here is what is odd though...
When I run:
myArray.sort( (a, b) => {
console.log(a.name);
console.log(b.name);
It logs the names perfectly fine. What am I missing??
Just to be a thorough little bit of context:
I am using this method after doing an HTTP call from an angular service.ts file and this array is being passed to my component and subscribed to. And I am using Angular, so this would be Typescript compiling to JavaScript. I also have another myArray.forEach()
method just below my sort()
method and that is working.
Upvotes: 2
Views: 12189
Reputation:
Is this what you want?
var a = [
{ name: "John" },
{ name: "Jack" },
{ name: "Bob" }
];
a.sort(function (a, b) {
if (a.name > b.name) return 1;
if (a.name < b.name) return -1;
return 0;
});
console.log(a);
Upvotes: 17
Reputation: 386560
You could use a comparison which works independently of the type of string or number, by moving numerical values to top.
var array = [{ name: 20 }, { name: 21 }, { name: 2 }, { name: 11 }, { name: 1 }, { name: 'John' }, { name: 'Jane' }, { name: 'Frank' }, { name: 'Mary' },]
array.sort((a, b) => (typeof a.name === 'string') - (typeof b.name === 'string') || a.name > b.name || -(a.name < b.name));
console.log(array);
Upvotes: 1