简体   繁体   中英

I need a way to swap elements between two arrays

I have an array, and another array with the same elements as the first one except I combined [0,1] indexed elements in the first one to be the element [0] index of the second array ... Is there a way to compare these two arrays and swap the first two elements of the first array by the first element in the second one, without changing the whole array content!?

example: var firstArray = ['hi','my','name','is','sam','andrew']; var secondArray = ['sam andrew'];

and can I still be able to do that even if ['sam andrew'] was an object with styles and icons and all that?

If you just want to swap the first two elements, you can store the elements in temporary variables and append them to the opposing array.

let temp1 = array1.shift();
let temp2 = array2.shift();

array1.unshift(temp2);
array2.unshift(temp1);

and can I still be able to do that even if ['sam andrew'] was an object with styles and icons and all that?

The example makes proper use of references, so yes, that would still be possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM