# Sorting an array including the elements present in the subarrays in JavaScript

In the given problem statement we are asked to sort an array including the elements present in the subarrays with the help of javascript functionalities. As we talk about sorting any list or array the sort() and flat method is useful.

## What are sort(), flat() and isArray() methods in JavaScript ?

Let's understand the working of sort, flat and isArray methods in JavaScript.

The sort() method is basically used to sort the elements of an array and returns the sorted array. The items are sorted in dictionary order by default. But we can provide a function as an argument to sort the items in a different manner. For example:

input - arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
arr.sort((a, b) => a - b); // in ascending order
output -  [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]


The flat() function is used to flatten an array by concatenation subarrays. It flattens the array one level deep by default. But we can provide a number to flatten the array to a certain depth. For example:

input -  arr = [1, [2, 3], [4, [5, 6]]];
const flatArr = arr.flat();
output - [1, 2, 3, 4, 5, 6]


isArray() is a built−in javascript function. With the help of this function we can determine that the given value is an array or not. It gives boolean output indicating that the value is an array. For example:

Array.isArray([1, 2, 3]); // true
Array.isArray("hello"); // false
Array.isArray({"name": "John"}); // false


## Logic for The Above Problem

The easiest way to sort the items in an array with subarrays in javascript is by using the sort method and flat method.

For sorting an array which includes items present in the sub arrays in javascript, we can use the flat() method of javascript to flatten the array and then we can use the sort method to sort the items.

In our algorithm, the flat method of javascript will be used to flatten the array into a one dimensional array and the sort method will sort this array in ascending order. If we want to sort the sub arrays themselves instead of flattening them, we can use the map function to iterate the array items and sort them individually.

### Algorithm - First Approach

Step 1 − Create an array which contains sub arrays.

Step 2 − Define a flatArr variable and apply the flat method on the created arr.

Step 3 − After flattening the array arr we will now sort the array with the sort method.

Step 4 − Show the output on console

### Example

const arr = [4, 2, [5, 1], 3, [6]];

// Flatten the array
const flatArr = arr.flat();
// Sort the flattened array
flatArr.sort((a, b) => a - b);
console.log("After sorting the elements from subarray");
console.log(flatArr);


### Output

After sorting the elements from subarray
[ 1, 2, 3, 4, 5, 6 ]


### Algorithm − Second Approach

Step 1 − Declare an empty array called flatArr

Step 2 − Define a helper method called flattenHelper that is taking an array as its parameter and performs iteration over each and every item of the array.

Step 3 − If the item is present in an array then call the flattenHelper function recursively on the element.

Step 4 − If the element is not present in the array then push it into the flatArr.

Step 5 − Now call the flattenHelper function with the input array arr.

Step 6 − Following the fifth step, sort the flatArr in ascending order using the sort() method with a callback function that checks two items.

Step 7 − At last returns the flatArr as an output.

### Example

function flattenAndSort(arr) {
const flatArr = [];

// A function to recursively flatten and push elements into flatArr
function flattenHelper(arr) {
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {

// recursively flatten subarray
flattenHelper(arr[i]);
} else {
// push element into flatArr
flatArr.push(arr[i]);
}
}
}

flattenHelper(arr);
// sort flatArr in ascending order
flatArr.sort((a, b) => a - b);

return flatArr;
}

// example usage
const arr = [4, 2, [5, 1], 3, [6]];
const sortedArr = flattenAndSort(arr);
console.log(sortedArr);


### Output

[ 1, 2, 3, 4, 5, 6 ]


## Complexity

The above mentioned code is using the flat() function to flatten the array and then we have used the sort method to sort the array. This method has a time complexity of O(n log n). In this n is the total number of items in the array. The worst case time complexity of the sort method is O(n log n).

## Conclusion

An array which contains items present in subarrays depends on the size of the array and the complexity of the problem. We have seen that the flat method is a simple and good approach to flatten small arrays.

Updated on: 23-Aug-2023

59 Views