Sylvia
Sylvia

Reputation: 277

How to make an array automatically change when other array's sequence changes?

There are tow correlative arrays.

How to make an array change when other array's sequence changes with Javascript?

For instance,array1(1,3,2),array2(3,2,1), I need array 2 to become(2,1,3)when I make array 1 in descending order(3,2,1)?

Thank you very much!!

Upvotes: 1

Views: 163

Answers (1)

Kishan Rajdev
Kishan Rajdev

Reputation: 1965

I think this is what you want,

Assuming both arrays have same length, so whenever i am changing positions of 2 elements of array, will need to change the positions of elements of other array as well.

var array1 = [1,3,2];
var array2 = [3,2,1];
var swapArrayElements = function(index1, index2) {
  var temp1 = array1[index1];
  array1[index1] = array1[index2];
  array1[index2] = temp1;

  var temp2 = array2[index1];
  array2[index1] = array2[index2];
  array2[index2] = temp2;
};

swapArrayElements(0,2); //out: array1[2, 3, 1] & array2[1, 2, 3]
swapArrayElements(0,1); //out: array1[3, 2, 1] & array2[2, 1, 3]

Or another approach,

const array1 = [1,3,2];
const array2 = [3,2,1];

const swapArrayElements = function (x, y, arr) {
  if (arr.length === 1 || x >= arr.length || y >= arr.length) return arr;
  arr.splice(y, 1, arr.splice(x, 1, arr[y])[0]);
};

const swapArrays = (i1, i2, ...args) => {
  for(let i = 0; i < args.length; i++) {
    swapArrayElements(i1, i2, args[i]);
  }
}
swapArrays(0, 2, array1, array2); //out: array1[2, 3, 1] & array2[1, 2, 3]
swapArrays(0, 1, array1, array2); //out: array1[3, 2, 1] & array2[2, 1, 3]

Hope this helps.

Upvotes: 2

Related Questions