Sorting JSON Array by Multiple Keys with JavaScript

JavaScript’s sort() method sorts the elements of an array. Sort() takes callback where you can specify sorting rules.

By writing a small callback function,  array of JSON data can be easily sorted. In this example, we use the JSON array that has name and sore. We will sort this date first by score in a descending order and then alphabetical order by name if two people have the same score.

[{ name: "John", score: "432"},
 { name: "Joe", score: "125"},
 { name: "Zoe", score: "320"},
 { name: "Ziggy", score: "532"},
 { name: "Dave", score: "211"},
 { name: "Sarah", score: "621"},
 { name: "Alex", score: "320"}]

Now, here is the call back function that first sort by the first key and second key if the first key has the same value.

When the first key comparison is equal, it goes into the second sorting logic. For descending order sorting, we can return -1 when the first key is bigger than the second key. If you swap the returning value, the sorting order becomes ascending. Magic!

Now, all you need to do is to use this function in a callback for sort().

data.sort(rankingSorter("score", "name"));

Let’s check out how this can be used in the front end. I used pure JavaScript to inject HTML elements. I never really use this method, but sometimes fun to get back to the classic javascripting! To write the injection part, I referred to this page.

It sorts the JSON array and output as a list.

Ranking
    1. Name: Sarah, Score: 621
    2. Name: Ziggy, Score: 532
    3. Name: John, Score: 432
    4. Name: Zoe, Score: 320
    5. Name: Alex, Score: 320
    6. Name: Dave, Score: 211
    7. Name: Joe, Score: 125

Front-End
TypeScript: type aliases to check type equality

This post is to analyse how the type equality check by using type aliases proposed by Matt Pocock in his twitter post. These type aliases allow us to elegantly express type equality checks in unit tests. All we need to do is to pass the output and expected types in …

Front-End
Fixing it.only type error in Jest

If you are getting a type error with it.only in Jest, it could be due to incorrect TypeScript typings or incompatible versions of Jest and TypeScript. To resolve this issue, you can try the following steps: Make sure you have the latest versions of Jest and its TypeScript typings installed …

Front-End
yup conditional validation example

Here’s an example of a Yup validation logic where the first input field is optional but, if filled, it must contain only alphabetic characters, and the second input field is required: import * as Yup from “yup”; const validationSchema = Yup.object().shape({ firstField: Yup.string().matches(/^[A-Za-z]*$/, { message: “First field must contain only …