My Logo

Menu

  • Home
  • Archives
  • Tags
  • About
  • RSS

Implement Your Own Sort Function in JavaScript

May 12, 2023

implement custom sort function in javascript

Tags: [ javascript ]

  1. Prerequisites
  2. The Custom Sort Function
  3. Conclusion

In a previous article, I explained how one can use the in-built JavaScript sort() function. If you would like to know how you can implement your own sort function for numbers in an array, this article is for you. I am going to show you a function that's similar to the 'Quicksort' algorithm where we select a pivot and if we are sorting in ascending order, we send the numbers smaller than the pivot to a sub-array while greater numbers are sent to a different array and we recursively sort the sub-arrays then merge the sorted sub-array values with the pivot in between into one array.

Prerequisites

  • Node.js (this is optional since we only want somewhere we can run JavaScript, so it can be on a website browser or you can use Node on your machine)

The Custom Sort Function

You can create a JS file and name it customSort.js. Have the following code in it:

function customSort(array, order = 1) {
  if (array.length <= 1) {
    return array;
  }

  const pivot = array[0];
  const beforePivot = [];
  const afterPivot = [];

  for (let i = 1; i < array.length; i++) {
    if (
      (order === 1 && array[i] <= pivot) ||
      (order === 0 && array[i] >= pivot)
    ) {
      beforePivot.push(array[i]);
    } else {
      afterPivot.push(array[i]);
    }
  }

  const sortedBeforePivot = customSort(beforePivot, order);
  const sortedAfterPivot = customSort(afterPivot, order);

  return sortedBeforePivot.concat(pivot, sortedAfterPivot);
}

const numbers = [5, 3, 8, 1, 2, 9, 4];
console.log(customSort(numbers)); //ascending
console.log(customSort(numbers, 1)); //ascending
console.log(customSort(numbers, 0)); //descending

Our second function parameter (order) expects a 1 or 0 so that the function can tell whether we want to sort sort in ascending (1) or descending (0) order with the default being ascending order. Also, we can see that the first check in the function is to see if the array contains only one or no items.

You can run the file locally if you have Node.js installed:

node customSort.js

Conclusion

We have seen how you can sort the function using a function that does something similar to the 'Quicksort' algorithm. You can use a different sort algorithm. I may add custom sort functions using different sorting algorithms later on. I may also modify the function to add another check for whether array values are numbers or not or even sort strings later on.


Back to top ↑

Using sort() in JavaScript to Sort Items in an Array/Object »


Copyright © 2024 Brian Mulaa