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.
||operators, you would be best to add parentheses throughout, but really, you might want to go back to using something easier to debug using good old-fashionedif .. else