I would like to know why the following happens... Making a function that takes the value of the middle of three numbers I tried with the first idea that came to my mind is the function that is here below...
function valorMedio (inputArray) {
console.log(`arreglo original: [${inputArray}]`);
let mid = inputArray.sort((a,b) => a-b)[1]
console.log(`arreglo final: [${inputArray}]`);
return inputArray.indexOf(mid)
};
console.log(valorMedio([15, 22, -7]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
is simple; sort the array take the second number of the sorted array and assign it to a variable and then look up the index of this number in the original array. The problem is that the mutated array returns me index 1 when it should be index 0 , regardless of whether what I'm doing is taking a value from my original array, it's sorted... Which if I do eg: mid =inputArray.sort((a,b) => a-b).join('')
and all the complications don't happen later .. Normally if I want to change an array that I receive by parameter I do inputArray = inputArray.sort((a,b) => a-b)
array = array.modificaciones()
.
function valorMedio (inputArray) {
console.log(`arreglo original: [${inputArray}]`);
let mid = [...inputArray].sort((a,b)=>a-b)[1]
console.log(`arreglo final: [${inputArray}]`);
return inputArray.indexOf(mid)
};
console.log(valorMedio([15, 22, -7]));
console.log(valorMedio([1, -22, 75]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
I thought it was not strange I was assigning a reference... and I solved it by copying the array from this function above but the strange thing was that if I do:
function valorMedio2(a) {
return a.indexOf(a.sort((a, b) => a - b )[1])
}
function valorMedio3(a) {
return a.indexOf(a.concat().sort((a, b) => a - b )[1])
}
console.log('Incorrecto '+valorMedio2([15, 22, -7]));
console.log('Correcto '+valorMedio3([15, 22, -7]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
WITH IT concat()
I SOLVE THE PROBLEM... What happens in Javascript that mutates the array???
The method
sort
mutates the array and returns it. So it doesn't matter if you try to save the sort result to a new variable or not, since you'll still be working with the original array:On the other hand, the method
concat
creates a new array, so in each function you are asking it to search by index in two different arrays. So you can see the difference I have rewritten your functions making each step more explicit: