I'm facing an issue sorting an array of objects by a name property present on each object. When utilizing the sort()
method with the given code snippet, I encounter the following error:
ERROR ReferenceError: b is not defined
This is my code block:
myArray.sort( (a,b) => {
return (typeof a.name === 'string') - (typeof b.name === 'string') || a.name - b.name || a.name.localeCompare(b.name)};
What puzzles me is...
When I execute:
myArray.sort( (a,b) => {
console.log(a.name);
console.log(b.name);
It logs the names properly. What am I overlooking?
A little more context:
Following an HTTP call from an Angular service.ts file, I apply this method. The resulting array is then passed to my component and subscribed to. This is in the realm of Angular using TypeScript that compiles into JavaScript. Additionally, below my sort()
method, another forEach()
method operates without issues.