Computer >> Computer tutorials >  >> Programming >> Javascript

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


We are required to write a JavaScript function that takes in an array of arrays of integers. Each subarray within the array will contain exactly two integers.

The function should sort the array including the elements present in the subarrays.

For example: If the input array is −

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

Then the output array should be −

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

Output

The code for this will be −

const arr = [
   [4, 2],
   [6, 1],
   [5, 3]
];
const sortWithin = (arr = []) => {
   const res = [];
   const temp = [];
   for(let i = 0; i < arr.length; i++){
      temp.push(...arr[i]);
   };
   temp.sort((a, b) => a − b);
   for(let i = 0; i < temp.length; i += 2){
      res.push([temp[i], temp[i+1]]);
   };
   return res;
};

Output

And the output in the console will be −

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