Issue
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.
Solution
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);
Answered By - user1636522
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.