How to sorting an array without using loops in Node.js?


In Node.js, a built-in sort() method is available to sort an array without a headache. However, as a beginner to learn how the sort() method works internally, users should learn various sorting algorithms.

In this tutorial, we will learn a different algorithm to sort an array without using loops in NodeJS.

Use the setInterval() method

The setInterval() method allows us to invoke any particular function after each interval. Also, we can store the id of the setInterval() method in any variable and use it later to clear the interval.

So, we can call a callback function in the setInterval() method, which finds the minimum element from the array, pushes it to the sorted array and replaces the minimum element with an Infinity value.

Syntax

Users can follow the syntax below to use the setInterval() method to sort an array without a loop using NodeJS.

let interval = setInterval(sort_callback, 2);

// in sort_callback() function
let min_from_array = Math.min.apply(null, array);
sorted_Array.push(min_from_array);
array[array.indexOf(min_from_array)] = Infinity;
if (++len == array.length) {
   clearInterval(interval);
} 

Steps

Step 1 – Use the setInterval() method to call the sort_callback() function after every 2 seconds

Step 2 – Use the Math.min.apply() method to get the minimum element from the array.

Step 3 – Push the minimum element to the array.

Step 4 – Use the index of the minimum element, and replace the minimum element with the infinity value.

Step 5 – If the value of the len variable is equal to the array length, it means all array elements are sorted and clear the interval to stop executing the sort_callback() function via the setInterval() method.

Example

In the example below, we have created the numeric array and applied the above algorithm to sort the array in ascending order. Users can use the Math.max.apply() method to sort the array in descending order and assign negative Infinity values to the maximum element.

let array = [10, 20, 45, 21, 32, 11, 9, 8, 65];
console.log("The original array is");
console.log(array);
let interval = setInterval(sort_callback, 2);
let len = 0;
let sorted_Array = [];
function sort_callback() {
   let min_from_array = Math.min.apply(null, array);
   sorted_Array.push(min_from_array);
   array[array.indexOf(min_from_array)] = Infinity;
   len++;
   if (len == array.length) {
      clearInterval(interval);
      console.log("The sorted array is");
      console.log(sorted_Array);
   }
}

Use the array.reduce() method

We can keep extracting the minimum element from the array while every iteration of the array.reduce() method, and pushes it to the sorted_array. In such a way, we can get the sorted array once the execution of the reduce() method completes.

Syntax

Users can follow the syntax below to use the array.reduce() method to sort arrays without using loops in NodeJS.

arr.reduce((sorted_Array, element) => {
   let min_from_array = Math.min.apply(null, arr);
   sorted_Array.push(min_from_array);
   arr[arr.indexOf(min_from_array)] = Infinity;
   return sorted_Array;
}, []);

In the above syntax, we extract the minimum element from an array, push it into an array, replace the minimum element with infinity and return the sorted array from reduce() method.

Example

In the example below, the sort_array() function uses the reduce() method to sort the array. Once the iterations of reduce() method are completed, we return the sorted array from the function.

let arr = [
   100, 99, 32, 45, 6567898, 32, 123, 54, 7, 89, 745, 43, 34, 232, 121, 23, ];
console.log("The original array is " + arr);
function sort_array() {
   return arr.reduce((sorted_Array, element) => {
      let ind = 0;
      let min_from_array = Math.min.apply(null, arr);
      sorted_Array.push(min_from_array);
      arr[arr.indexOf(min_from_array)] = Infinity;
      return sorted_Array;
   }, []);
}
console.log("The sorted array is ", sort_array());

Users can spot the difference between the original and sorted array in the output.

Use the recursive solution

We will implement the recursive bubble-sort algorithm in this approach to sort the array. The bubble sort algorithm uses the two loops to iterate through the array, swap elements, and sort the whole array.

Here, we will replace the outer for loop with a recursive solution.

Syntax

Users can follow the syntax below to implement the recursive bubble-sort algorithm.

function recursive_sort(array, index) {
   if (index == 1)
   return;
   var count = 0;
   for (var i = 0; i < index - 1; i++)
   
   // swap array elements if it’s not sorted
   return recursive_sort(array, index - 1);
}

Steps

Step 1 – Write a base case first. If the index becomes equal to 1, execute the return statement.

Step 2 – Initialize the count variable with 0.

Step 3 – Use for loop to iterate through the array and swap elements if two elements are not sorted. When we swap elements, increase the value of the count by 1.

Step 4 – If the count value is 0, no more swap is required and returns from the function.

Step 5 – Make a recursive function call by decreasing the value index by 1, decreasing the one iteration.

Example

In the example below, we have used the recursive bubble sort function to sort an array in NodeJS. We have used the temporary variable to swap two variables.

var arr = [613, 65, 654, 4, 65, 4, 61, 631, 6513, 89, 7, 97, 09, 98];
console.log("The original array is " + arr);
function recursive_sort(array, index) {
   
   // return statement for the base case
   if (index == 1) return;
   var count = 0;
   
   // swap elements that are not in sorted order
   for (var i = 0; i < index - 1; i++)
   if (array[i] > array[i + 1]) {
      var temp = array[i];
      array[i] = array[i + 1];
      array[i + 1] = temp;
      count++;
   }
   
   // if any swap does not occur, execute the return;
   if (count == 0) return;
   
   // call recursive_sort index-1 times, to swap element index-1 times
   return recursive_sort(array, index - 1);
}
recursive_sort(arr, arr.length);
console.log("The sorted array is ", arr);

In the output, users can observe that array is swapped.

Users learned three different approaches to sorting the array without using the for loop in NodeJS. The best way to sort the array without using the for loop is to use the array.reduce() method as it is a more efficient approach. The recursive approach can give a memory limit error for the large array.

Updated on: 06-Mar-2023

749 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements