I have an array X = [12,14,12,45,12] and another array Y = [34,12,23,47,20]. I am sorting the X array, so now X = [12,12,12,14,45]. Now I want to sort Y as Y = [34,23,20,12,47]. Any help would be appreciated. Thanks
2 Answers
You can build an array of indexes and sort it using a custom comparator function that references X and, then, use that array to "sort" Y:
var X = [12,14,12,45,12];
var Y = [34,12,23,47,20];
var xIndexes = [];
X.forEach((value, index) => xIndexes.push(index));
xIndexes.sort((a, b) => X[a] < X[b] ? -1 : X[a] > X[b] ? 1 : 0);
var newX = [];
var newY = [];
xIndexes.forEach((index) => {
newX.push(X[index]);
newY.push(Y[index]);
});
console.log(newX);
console.log(newY);
Comments
You can combine the arrays into a single array. Sort by the original values of X, and then separate back into 2 arrays.
const X = [12,14,12,45,12];
const Y = [34,12,23,47,20];
const [Xsorted, Ysorted] =
X.map((x, i) => [x, Y[i]])
.sort((a, b) => a[0] - b[0])
.reduce((arrs, [x, y]) => {
const [X, Y] = arrs;
X.push(x);
Y.push(y);
return arrs;
}, [[], []]);
console.log(Xsorted);
console.log(Ysorted);