JavaScript Program to Sort an Array which Contain 1 to n Values
Last Updated :
29 Aug, 2024
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.
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 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);
OutputSorted 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);
OutputSorted 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);
OutputSorted Array is: [
0, 1, 2, 3, 4,
5, 9, 20, 100
]
Approach 4: Counting Sort
Counting Sort is a non-comparison-based sorting algorithm that operates in linear time complexity, O(n), making it very efficient for sorting integers within a specific range.
Steps:
- Create a Count Array:
- Initialize an array
count
where the index represents the number and the value at that index represents the count of that number.
- Count Occurrences:
- Traverse the input array and increment the count at the index corresponding to each element.
- Construct the Sorted Array:
- Traverse the count array and construct the sorted array based on the counts.
JavaScript
function countingSort(arr) {
if (arr.length === 0) return [];
// Step 1: Find the maximum value to determine the size of the count array
const maxVal = Math.max(...arr);
// Step 2: Initialize the count array with zeros
const count = new Array(maxVal + 1).fill(0);
// Step 3: Count the occurrences of each value
arr.forEach(num => count[num]++);
// Step 4: Construct the sorted array
const sortedArr = [];
count.forEach((numOccurrences, value) => {
for (let i = 0; i < numOccurrences; i++) {
sortedArr.push(value);
}
});
return sortedArr;
}
let inputArray = [3, 1, 4, 5, 2, 8, 9, 5];
const sortedArray = countingSort(inputArray);
console.log("Sorted Array is:", sortedArray);
OutputSorted Array is: [
1, 2, 3, 4,
5, 5, 8, 9
]
Similar Reads
JavaScript Program for Insertion Sort What is Insertion Sort Algorithm?Insertion sorting is one of the sorting techniques that is based on iterating the array and finding the right position for every element. It compares the current element to the predecessors, if the element is small compare it with the elements before. Move ahead to a
4 min read
JavaScript Program for Quick Sort What is Quick Sort Algorithm?Quick sort is one of the sorting algorithms that works on the idea of divide and conquer. It takes an element as a pivot and partitions the given array around that pivot by placing it in the correct position in the sorted array. The pivot element can be selected in the f
4 min read
Javascript Program to Sort an array in wave form Given an unsorted array of integers, sort the array into a wave like array. An array 'arr[0..n-1]' is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= .....Examples: Input: arr[] = {10, 5, 6, 3, 2, 20, 100, 80} Output: arr[] = {10, 5, 6, 2, 20, 3, 100, 80} OR {
4 min read
Javascript Program For Sorting An Array Of 0s, 1s and 2s Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last.Examples:Input: {0, 1, 2, 0, 1, 2}Output: {0, 0, 1, 1, 2, 2}Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}Output: {0, 0, 0, 0, 0
5 min read
Java Program to Print the Smallest Element in an Array Java provides a data structure, the array, which stores the collection of data of the same type. It is a fixed-size sequential collection of elements of the same type. Example: arr1[] = {2 , -1 , 9 , 10} output : -1 arr2[] = {0, -10, -13, 5} output : -13 We need to find and print the smallest value
3 min read