I'm new to JS and am trying to create a simple 'swap array elements if array A element is bigger than array B element' function. In the swapIndexes function, I don't understand why I can't define the variables as shown in the comments. For example, it works if it state arrA[c] rather than let a = arrA[c].
Why does this happen? Can anyone give some beginner tips on how best to go about something like this? My code feels verbose. Thanks for any help here.
var arrA = [0, 1, 2, 7, 6],
arrB = [0, 1, 2, 5, 7],
indexesToSwap = [],
aValuesToSwap = [],
bValuesToSwap = [],
needSwapping = false;
arrA.forEach(getSwappableIndexesAndValues);
indexesToSwap.forEach(swapIndexes);
function getSwappableIndexesAndValues(c, i) {
let b = arrB[i];
if (c > b) {
needSwapping = true;
indexesToSwap.push(i);
aValuesToSwap.push(b);
bValuesToSwap.push(c);
}
}
function swapIndexes(c, i) {
//let a = arrA[c]; fails why???
//let b = arrB[c]; fails why???
//a = aValuesToSwap[i]; fails why???
//b = bValuesToSwap[i]; fails why???
arrA[c] = aValuesToSwap[i];
arrB[c] = bValuesToSwap[i];
}
console.log(arrA);
console.log(arrB);
indexesToSwapis empty as I seearrA[c] = aValuesToSwap[i]; arrB[c] = bValuesToSwap[i];This operation is meaning less reassigning same values. This may be your logical error.let a = arrA[c]you have to ask yourself "is arrA[c] a simple type?" (a number, string or boolean). If so you get a copy of that value in a, otherwise you get a reference to whatever the object at arrA[c] is. Since your values are all simple values, you don't get references to work with.let a = cthen you're just assigning the variableato be equal to a number and thus you are not modifying the array itself. Same goes for your commented out codelet a = arrA[c];etc..., you are just settingato be a number ("copied" out of the array, but when modified not modified in the array itself), so when you overwritealater on your just overwriting a number which has no connection to the original array.