I'm trying to practice by doing the following exercise:
Write a function that takes a numeric array and returns an object containing two arrays. The first one should have the elements sorted in ascending order, and the second one should have them in descending order.
This is the code without the validation portion (which I know for a fact is not causing any troubles):
function ascDesc(arr) {
let ascending = arr.sort((a,b) => a - b);
let descending = arr.sort((a,b) => b - a);
console.log({ ascending, descending });
}
ascDesc([7,5,2,7,8,6,10,-10]);
This is returning both arrays sorted the same way. I know .sort()
doesn't return a new array, and I'm assuming this has something to do with that, but still I don't understand why it is happening, since I'm storing things in two separate variables.
Could someone help me understand? I've already solved it by adding .map(e => e)
before the .sort()
method. Tried googling and searching here but couldn't seem to find an answer, and MDN is not helping.