Open In App

JavaScript Program to Sort an Array which Contain 1 to n Values

Last Updated : 18 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will Sort an array that contains 1 to n values in JavaScript. There are different approaches through which we can sort an array. So, we will mainly cover three different approaches.

Approaches to Sort an array that contains 1 to n values in JavaScript

  • Using the Set collection in JavaScript
  • Using the reduce() method in JavaScript
  • Using the recursive and minimum element

We will explore all the above methods along with their basic implementation with the help of examples.

Approach 1: Using the Set collection in JavaScript

In this approach, we are basically using the Set data structure which has the feature to discard the duplicates from the given input array. Here, we are converting the Set back to an array and then sorting it, this results in us getting the sorted array that contains the unique elements in the array. This is the efficient approach while working with the values that should be included only once.

Syntax

const mySet = new Set(iterable);
const sortedArray = Array.from(mySet).sort((a, b) => a - b);

Example: In this example, we will find the sort using the Set Collection Approach.

Javascript




//Using Set Collection
let inputArray = 
    [3, 1, 4, 5, 2, 8, 9, 5];
const newSortedArray = 
    Array.from(new Set(inputArray)).sort(
    (a, b) => a - b
);
console.log("Sorted Array is:", newSortedArray);


Output

Sorted Array is: [
  1, 2, 3, 4,
  5, 8, 9
]

Approach 2: Using the reduce() method in JavaScript

In this approach, we are going to use the reduce() method in JavaScript that initially goes through the element of the array and inserts each element value to its correct index within the accumulator array. We have used the findIndex() function in the code that specifies the insertion point and the splice() function that inserts the value to the position where we are maintaining the sorted order of the elements.

Syntax

array.reduce(callbackfunc, initialValue);

Example: In this example, we will sort using the reduce() method in JavaScript.

Javascript




// Using reduce() method
let inputArray = [3, 1, 4, 5, 2, 0, 10];
const newSortedArray = inputArray.reduce(
    (callbackfunc, element) => {
        const index = callbackfunc.findIndex(
            (item) => element <= item
        );
        index === -1
            ? callbackfunc.push(element)
            : callbackfunc.splice(index, 0, element);
        return callbackfunc;
    },
    []
);
  
console.log("Sorted Array is:", newSortedArray);


Output

Sorted Array is: [
  0, 1,  2, 3,
  4, 5, 10
]

Approach 3: Using the recursive and minimum element Approach

In this approach, we recursively find the minimum element in the given array and then we construct the sorted output array by repeatedly retrieving the smaller element and appending it to the result array. This approach efficiently sorts the array from the smaller to greater elements by selecting the minimum element from the array repeatedly.

Syntax

function sortingUsingMinRecursiveApproach(arrayElements) {
// ...
}
function recursiveSortFunc(element) {
// ...
}
let inputArray = [/* ... */];
const outputArray = recursiveSortFunc(inputArray);

Example: In this example, we will sort using the recursive and minimum elements in JavaScript.

Javascript




//Using recursive and minimum element
let inputArray = [100, 20, 0, 9, 3, 1, 4, 5, 2];
function sortingUsingMinRecursiveApproach(arrayElements) {
    let minElementIndex = 0;
    for (let i = 1; i < arrayElements.length; i++) {
        if (
            arrayElements[i] <
            arrayElements[minElementIndex]
        ) {
            minElementIndex = i;
        }
    }
    return arrayElements.splice(minElementIndex, 1)[0];
}
function recursiveSortFunc(element) {
    if (element.length === 0) {
        return [];
    }
    const minEle =
        sortingUsingMinRecursiveApproach(element);
    return [minEle, ...recursiveSortFunc(element)];
}
const outputArray = recursiveSortFunc(inputArray);
  
console.log("Sorted Array is:", outputArray);


Output

Sorted Array is: [
  0, 1,  2,   3, 4,
  5, 9, 20, 100
]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads