![]() |
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
We will explore all the above methods along with their basic implementation with the help of examples. Approach 1: Using the Set collection in JavaScriptIn 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. Syntaxconst mySet = new Set(iterable); Example: In this example, we will find the sort using the Set Collection Approach. Javascript
Output
Sorted Array is: [ 1, 2, 3, 4, 5, 8, 9 ] Approach 2: Using the reduce() method in JavaScriptIn 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. Syntaxarray.reduce(callbackfunc, initialValue);
Example: In this example, we will sort using the reduce() method in JavaScript. Javascript
Output
Sorted Array is: [ 0, 1, 2, 3, 4, 5, 10 ] Approach 3: Using the recursive and minimum element ApproachIn 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. Syntaxfunction sortingUsingMinRecursiveApproach(arrayElements) { Example: In this example, we will sort using the recursive and minimum elements in JavaScript. Javascript
Output
Sorted Array is: [ 0, 1, 2, 3, 4, 5, 9, 20, 100 ] |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |