I'm trying to define an array b
to be an independent copy of an array argument a
.
Thus, I want to change b
without changing a
.
But here is a mystery: When I sort b
, a
is sorted as well!
function firstDuplicate(a) {
let b = a;
console.log(`this is a : ${a}`) // this is a : 2,1,3,5,3,2
console.log(`this is b : ${b}`) // this is b : 2,1,3,5,3,2
b.sort()
console.log(`this is a : ${a}`) // this is a : 1,2,2,3,3,5 (my problem)
console.log(`this is b : ${b}`) // this is b : 1,2,2,3,3,5
}
firstDuplicate([2, 1, 3, 5, 3, 2])
How can I avoid this?
Thank you so much for your replies.