

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 parts of array separately in JavaScript
We have an array that contains many objects. We are required to write a function to sort the first half of the array in ascending order.
And the second half of the array with ascending order to but without inter mixing the entries of halves into one another.
Consider this sample array −
const arr = [ {id:1, x: 33}, {id:2, x: 22}, {id:3, x: 11}, {id:4, x: 3}, {id:5, x: 2}, {id:6, x: 1} ];
Our function should sort this array on the basis of the 'x' property of the objects keeping the things mentioned above in mind.
Example
The code for this will be −
const arr = [ {id:1, x: 33}, {id:2, x: 22}, {id:3, x: 11}, {id:4, x: 3}, {id:5, x: 2}, {id:6, x: 1} ]; const sortInParts = array => { const arr = array.slice(); const sorter = (a, b) => { return a['x'] - b['x']; }; const arr1 = arr.splice(0, arr.length / 2); arr.sort(sorter); arr1.sort(sorter); return [...arr1, ...arr]; }; console.log(sortInParts(arr));
Output
And the output in the console will be −
[ { id: 3, x: 11 }, { id: 2, x: 22 }, { id: 1, x: 33 }, { id: 6, x: 1 }, { id: 5, x: 2 }, { id: 4, x: 3 } ]
- Related Questions & Answers
- Sorting odd and even elements separately JavaScript
- Get Date and Time parts separately in Java
- Extract arrays separately from array of Objects in JavaScript
- Uneven sorting of array in JavaScript
- Alternative sorting of an array in JavaScript
- Sorting Array Elements in Javascript
- Parts of array with n different elements in JavaScript
- Sorting an array of binary values - JavaScript
- Sorting an array of objects by an array JavaScript
- JavaScript array sorting by level
- Sorting Array based on another array JavaScript
- Sorting JavaScript object by length of array properties.
- Sorting only a part of an array JavaScript
- Sorting array of Number by increasing frequency JavaScript
- Sorting digits of all the number of array - JavaScript
Advertisements