1

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

1
  • 1
    1. What's the logic behind sorting Y 2. Did you try to solve it yourself? Please show some code. Commented Jul 6, 2017 at 7:03

2 Answers 2

4

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.