2

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.

8
  • 3
    please add the array as well. Commented Mar 17, 2018 at 15:13
  • 1
    The subtraction operator doesn't work on string values; what is it that you expect that expression to do? Commented Mar 17, 2018 at 15:14
  • Doesn't look like valid typescript syntax to me. Commented Mar 17, 2018 at 15:15
  • 1
    With that many || 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-fashioned if .. else Commented Mar 17, 2018 at 15:17
  • 1
    Please add a minimal, complete and verifiable example which shows the actual problem. Commented Mar 17, 2018 at 15:20

2 Answers 2

17

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);

Sign up to request clarification or add additional context in comments.

2 Comments

This worked. Thank you! I am new to TypeScript and working out some of the kinks. Maybe I should maybe just stick to writing JS for my projects
@newman As you wish, I guess you know that TypeScript is a superset of JavaScript, hence you can use JS when you are not sure how to do it with TS :-)
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.