(UPDATED).
I am trying to sort 2 arrays of object in same time.
I have an array of object contain date.
firstArray = [{date: timestamp0 ...},
{date: timestamp1 ...},
{date: timestamp2 ...},
{date: timestamp3 ...},
]
I have a second array with the same length as the first array contains location (x,y).
secondArray = [{x: number0 ..., y: number0},
{x: number0 ..., y: number0},
{x: number0 ..., y: number0},
{x: number0 ..., y: number0},
]
Every object in the first array is related to object in second array that mean:
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 said every object is related.
How to sort the second array in same order like first array?
Sorting firstArray:
firstArray.sort(function (a, b) {
return new Date(b.date) - new Date(a.date);
});
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
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)