- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ] ]
- Related Articles
- Commons including duplicates in array elements in JavaScript
- Finding array intersection and including repeating elements in JavaScript
- Count unique elements in array without sorting JavaScript
- Sorting an array by date in JavaScript
- Sorting an array by price in JavaScript
- Alternative sorting of an array in JavaScript
- Sorting array according to increasing frequency of elements in JavaScript
- Sorting array of exactly three unique repeating elements in JavaScript
- Sorting array based on increasing frequency of elements in JavaScript
- Sorting an array that contains undefined in JavaScript?
- Sorting an associative array in ascending order - JavaScript
- Print the Elements of an Array Present in Odd Positions in Java
- JavaScript Return an array that contains all the strings appearing in all the subarrays
- Sorting an array of objects by an array JavaScript
- Total number of elements present in an array in C#

Advertisements