mercredi 26 juin 2019

Only sort pairs in array

I have an array of objects, like this for example:

  const arr = [
  {
    type: 2,
    name: 'A',
  },
  {
    type: 1, 
    name: 'B'},
  {
    type: 2, 
    name: 'C'},
  {
    type: 1,
    name: 'D',
  },
];

Now what you don't see is, there are pairs of objects. So "A" and "B" belong together. Now I want to sort this array, so in the end it becomes this:

const result = [
  {
    type: 1,
    name: 'B',
  },
  {
    type: 2, 
    name: 'A'},
  {
    type: 1, 
    name: 'D'},
  {
    type: 2,
    name: 'C',
  },
];

So basically I only want to sort the pairs.

I tried using the indexes like here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Sorting_with_map

And basically just use the modulo operator for the index of the current value, but I fear the sort mechanism works a bit differently.




Aucun commentaire:

Enregistrer un commentaire