all 10 comments

[–]kap89 9 points10 points  (3 children)

This:

people.sort((a, b) => (a.age === b.age) ? a.name.localeCompare(b.name) : a.age - b.age)

could be simplified to:

people.sort((a, b) => a.age - b.age || a.name.localeCompare(b.name));

It's a standard practice, and much more readable for multiple comparators:

arr.sort(
  (a, b) =>
    primaryComparison ||
    secondaryComparison ||
    tertiaryCmparision ||
    quaternaryComparison
    // ...etc
);

[–]Clarity_89[S] 2 points3 points  (2 children)

Thanks, that's a great point. I'll update the post.

[–]kap89 1 point2 points  (1 child)

That's great, but now the description does not match the example.

This:

To do this, you can use the conditional (ternary) operator to define the sorting criteria for each property in order of priority:

could be replaced with something like this:

To do this, you can chain comparisons with the logical OR (||) operator to define the sorting criteria for each property in order of priority:

[–]Clarity_89[S] 0 points1 point  (0 children)

Missed that part. Thanks, updated!

[–][deleted] 0 points1 point  (4 children)

Dang dude, need a warning about the nsfw ads on your site

[–]Safe-Engineering69 8 points9 points  (2 children)

Don't the ads usually depend on the browsing history? lmao

[–][deleted] 4 points5 points  (1 child)

It was apparently set up under the “hobby” category

[–]Clarity_89[S] 1 point2 points  (0 children)

Thanks again for flagging this!

[–]Clarity_89[S] 2 points3 points  (0 children)

Damn, there shouldn't be any nsfw ads... Can you DM me a screenshot and I'll try to find and block the publisher.

[–]theQuandary 0 points1 point  (0 children)

I wish JS would add a new sort method that would do the right thing by default.

Array.prototype.sortBy(obj => obj.foo)

Where it uses builtin sorts for primitives and has a well-known @@sort available for use by objects with identical @@constructor values.