sorting array of numbers into sets in JavaScript


In the given problem statement we are asked to sort an array of numbers into some sets where the array is the input source provided by the user going from brute force method to optimized solution .

What is an array in JavaScript ?

If you are familiar with any other programming language like C, C++, or Java, you must have heard the term 'array.'

In programming, an array is a collection of similar data elements under one roof.

Now, an important question arises: if arrays are generally the same in all languages, then how does JavaScript make arrays more unique and usable?

Let's understand the overall working of arrays in JavaScript.

An array is an object that stores multiple elements. Since an array is also an object, it has some properties and methods that make working with arrays easier in JavaScript.

Example

Following is the syntax to define Arrays in JavaScript : -

const arrayExample  = [ 100 , 200 , 500 ,600 ];
console.log(arrayExample);

Output

[ 100, 200, 500, 600 ]

What is the Sort Method in JavaScript ?

The sort method in javascript sorts the array inplace and results in the sorted array in ascending order by default . But JavaScript language has a catch here , it first converts every single element you want to sort into a string data type and then the sorting is performed.

In JavaScript the sort method in behind the scenes do not just do comparison like many other programming languages do for sorting but here once each element is when converted into string initially these conversions are solely based on UTF-16 followed by the order of element comes in the table while converting , that decides the sorting parameter of sort method in JavaScript. UTF-16 allows more characters and emojis in your domain , hence efficient and large scale sorting is wished for.

The example will make you understand the sort method in Javascript more :

const arrOfNumbers = [ 10 , 5 , 1 ] ;

console.log(arrOfNumbers.sort());

Expected Output 
[ 1 , 5 , 10 ] 

Real Output 

[ 1, 10, 5 ]

The output looks weird right because this is how sorting behaves behind the scenes in javascript due to its string conversion step . Here the sorting works efficiently with string data type .

const strOfNumbers = ['c', 'z', 'a'];
console.log(strOfNumbers.sort());
Expected Output 
[ 'a', 'c', 'z' ]
Real Output 
[ 'a', 'c', 'z' ]

This is where one should understand the spotlight of the problem statement , as we need to sort an array of numbers first to put it in a set data structure form .

Sort on Array of Numbers

Sorting on an array of numbers requires a helper function called compare() which compares and contrasts the numbers present in the array based on the number data type.

A compare function can return negative , zero or positive numbers which can become the basis of sorting algorithms.

The example will make you understand the sort method applied on number data type in Javascript more :

const arrOfNumbers = [10, 5, 1];
console.log(arrOfNumbers.sort((x, y) => x - y));
Expected Output 
[ 1, 5, 10 ]
Real Output 
[ 1, 5, 10 ]

What is Set in JavaScript ?

Set in JavaScript was introduced in es6 is a collection of elements where every element present in the Set must uphold the uniqueness of nature and discards the duplicacy. Also Set does not maintain the order of elements in the way you have added the elements because Set does not maintain the index property to pillar the order of elements .

Example

The following example illustrates set :

const setStringArray = new Set("javascript");
console.log(setStringArray);

Output

Set { 'j', 'a', 'v', 's', 'c', 'r', 'i', 'p', 't' }

Example

The following example illustrates set :

const setNumberArray = new Set ( [ 1,2,3 ] );
console.log(setNumberArray);

Output

Set { 1, 2, 3 }

The problem statement talks about Set in relation to numbers , mind that the sort method does not directly work on Set , instead we need to work indirectly in such a case to sort an array of numbers first and then convert the array into set in JavaScript.

Algorithm

Step 1 : Declare a main function with name sortedArrayInSet that takes array of numbers as an input

Step 2: Taken array of numbers , will be sorted by another helper function with name sortArray that is a custom function to sort array of numbers as mentioned above hw sorting works behind the scenes in javascript .

Step 3: Because Set cannot be sorted directly , we had first an array of numbers as an input on which sorting mechanism was performed and then the array of numbers in sorted form is converted into Set datatype using new Set () functionality.

Step 4 : The resultant is sorted array of numbers into Set in javascript .

Example

function sortArray ( num1 , num2 )
{
  return num1 - num2 ;
};

function sortedArrayInSet ( arr )
{
   const finalSortedArray = arr.sort(sortArray);
   const finalSortedSet= new Set(finalSortedArray);
   console.log("sorted array of numbers into set " , finalSortedArray);
}

const arrOfNumbers = [ 20000 , 12 , -9 , 23 , 100 , -76 ];
sortedArrayInSet(arrOfNumbers);

Output

sorted array of numbers into set :  [ -76, -9, 12, 23, 100, 20000 ]

The following mentioned code is the straight forward code one can think of while looking at the problem statement , later you can ofcourse optimize it to the better quality of space and time making it more efficient and high quality.

In the above code we have declared a function taking in the array input . Then we go indirectly by knowing the sorting mechanism and sorting the array of numbers first using a custom function and then converting it into a set that solves the problem statement you can ask for.

Time Complexity

Array.sort () method is based on the Time sort algorithm , giving the time complexity of O (n log n) and in the worst case , time complexity goes to O ( n^2).

Conclusion

This is how we can solve the above problem statement thinking logically and in the context of coding taking help of javascript method sort and data type set in its most efficient use case .

Updated on: 22-Aug-2023

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements