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 }
]

Updated on: 21-Nov-2020

129 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements