Home > OS >  sort 2 array of object in same time in javascript
sort 2 array of object in same time in javascript

Time:09-29

(UPDATED).

i am trying to sort 2 array of object in same time.

i have a array of object contain date.

firstArray = [{date: timestamp0 ...},
              {date: timestamp1 ...},
              {date: timestamp2 ...},
              {date: timestamp3 ...},
             ]

i have second array with same length with the first array contain location (x,y).

secondArray = [{x: number0 ..., y: number0},
              {x: number0 ..., y: number0},
              {x: number0 ..., y: number0},
              {x: number0 ..., y: number0},
              ]

every object in first array is related to object in second array that mean :

for firstArray[0] is related to secondArray[0] and same for all.

after sorting first array output is (example) :

firstArray = [{date: timestamp3 ...},
              {date: timestamp1 ...},
              {date: timestamp2 ...},
              {date: timestamp0 ...},
             ]

i want to sort secondArray to be same as firstArray, beacuse as i say every object is related.

how to sort second array in same time like first array?

sorting firstArray:

firstArray.sort(function (a, b) {
  return new Date(b.date) - new Date(a.date);
});

CodePudding user response:

Add the original index before sorting:

const firstArray = [
{ date: "12/12/2021" }, 
{ date: "12/11/2021" },
{ date: "12/13/2021" },
{ date: "12/3/2021"  }];

firstArray.forEach((item, i) => item.orgIdx = i)
console.log(firstArray)

firstArray.sort((a,b)=> new Date(a.date)- new Date(b.date))
console.log(firstArray)


const secondArray = [
{ x: "number12" },
{ x: "number11" },
{ x: "number13" },
{ x: "number3"  }];

const secondArrSorted = new Array(secondArray.length)
firstArray.forEach(({orgIdx},i) => secondArrSorted[i] = secondArray[orgIdx]);
console.log(secondArrSorted)

CodePudding user response:

Basically take the indices, sort as wanted and map the values to new arrays.

const
    array1 = [], // given data
    array2 = [], // given data
    indices = [...array1.keys()].sort((a, b) => array1[a] - array1[b]), // or other sorting callback
    sortedArray1 = indices.map(i => array1[i]),
    sortedArray2 = indices.map(i => array2[i]);
    
console.log(sortedArray1); // sorted array1
console.log(sortedArray2); // sorted array2
  • Related