Sorting of Array of Objects not working with Array.sort() method

201
March 18, 2018, at 01:13 AM

I am attempting to sort an array of objects by a name property that exists on each object. When use 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 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.

Answer 1

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

Answer 2

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

READ ALSO
Javascript function input not calculating

Javascript function input not calculating

Hi in the code below I designed a very simple html page that will prompt a JavaScript pop up once openedThe function itself works when I run it in a simple compiler i

190
i want to add coding to a picture i downloaded for a subscribe button

i want to add coding to a picture i downloaded for a subscribe button

i want to add a basic subscribe button to my website i have downloaded a picture is there any way to code it so users can type there own email

99
JS: Play clip on mouseover

JS: Play clip on mouseover

I want to fire a clip on mouseover and it doesn't workI can log to the console but it seems I am doing something wrong to play the clip … What is it?

145
Ramda - appendPath

Ramda - appendPath

I'm starting on new project which uses Ramda and I'm looking for some function to append item to array on given pathIn Immutable

152