Home > Mobile >  Is this possible to sort one array according to the sorting order obtained by sorting another array?
Is this possible to sort one array according to the sorting order obtained by sorting another array?

Time:04-16

Here I have two arrays in javascript code

const array1 = [200, 455.23, -306.5, 9000, -642.21, -133.9, 79.97, 1300];
const array2 = [
    '2019-11-18T21:31:17.178Z',
    '2019-12-23T07:42:02.383Z',
    '2020-01-28T09:15:04.904Z',
    '2020-04-01T10:17:24.185Z',
    '2022-04-08T14:11:59.604Z',
    '2022-04-10T17:01:17.194Z',
    '2022-04-11T23:36:17.929Z',
    '2022-04-13T10:51:36.790Z',
];
array1.sort((a, b) => a - b);

Here I want array2 to be sorted exactly in the same order by which array1 is sorted. suppose that every element of both arrays at the same index has to be at the same index even after sorting array1. In short, I want to sort one array. And I want the other array sorted in exact same order.

CodePudding user response:

Here goes an example of how to implement the suggestion above, where both values are in one single array, like objects, and sorted by the value of each object in the array.

const myArray = [
  {date: '2019-11-18T21:31:17.178Z', value: 200},
  {date: '2019-12-23T07:42:02.383Z', value: 455.23},
  {date: '2020-01-28T09:15:04.904Z', value: -306.5},
  {date: '2020-04-01T10:17:24.185Z', value: 9000},
  {date: '2022-04-08T14:11:59.604Z', value: -642.21},
  {date: '2022-04-10T17:01:17.194Z', value: -133.9},
  {date: '2022-04-11T23:36:17.929Z', value: 79.97 },
  {date: '2022-04-13T10:51:36.790Z', value: 1300},
]

myArray.sort((a, b) => a.value - b.value)

CodePudding user response:

You can try this:

const array1 = [200, 455.23, -306.5, 9000, -642.21, -133.9, 79.97, 1300].map((e, index) => {
   return {
      value: e, 
      initialIndex: index
   } 
})
const array2 = [
    '2019-11-18T21:31:17.178Z',
    '2019-12-23T07:42:02.383Z',
    '2020-01-28T09:15:04.904Z',
    '2020-04-01T10:17:24.185Z',
    '2022-04-08T14:11:59.604Z',
    '2022-04-10T17:01:17.194Z',
    '2022-04-11T23:36:17.929Z',
    '2022-04-13T10:51:36.790Z',
];
function array_move(arr, old_index, new_index) {
    if (new_index >= arr.length) {
        var k = new_index - arr.length   1;
        while (k--) {
            arr.push(undefined);
        }
    }
    arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
    return arr; // for testing
};
array1.sort((a, b)=> a.value - b.value);
array1.forEach((el,index)=>{
   array_move(array2, el.initialIndex, index);
})
  • Related