I was trying to solve the Water Connection Problem
I have an inputs array
const inputs = [
[7, 4, 98],
[5, 9, 72],
[4, 6, 10],
[2, 8, 22],
[9, 7, 17],
[3, 1, 66]
]
when I pass an element of that array's inner array into splice() method like newArray.splice(-2, 0, item[1])
the original one, input[item]
is getting mutated.
Here is the full code
const inputs = [
[7, 4, 98],
[5, 9, 72],
[4, 6, 10],
[2, 8, 22],
[9, 7, 17],
[3, 1, 66]
]
const starts = inputs.filter(element =>
!(inputs.map(item => item[1]).includes(element[0]))
);
const arrayAppender = (array, element) => {
const newArray = element;
let elementAdd;
let traversalDone = false;
while (!traversalDone) {
elementAdd = false;
array.some(item => {
if (newArray[newArray.length - 2] === item[0]) {
newArray.splice(-1, 0, item[1]);
newArray[newArray.length - 1] = newArray[newArray.length - 1] > item[2] ? item[2] : newArray[newArray.length - 1];
elementAdd = true;
return true;
}
})
if (!elementAdd) traversalDone = true;
}
return newArray;
}
console.log(starts.sort().length);
starts.forEach((element, index) => {
starts[index] = arrayAppender(inputs, element);
console.log(starts[index][0], starts[index][starts[index].length - 2], starts[index][starts[index].length - 1]);
});
at the end of execution inputs[1]
changes from [5, 9, 72]
to [5, 9, 7, 4, 6, 10]
when I tried to see what causes the change, newArray.splice(-1, 0, item[1]) ;
this line of code was what's triggering it (found using debugger).
The code is working and doing what it's supposed to do, But I'm very much curious to see what's causing the above mentioned odd behavior and how can this be solved.
Thanks in advance.