0

I've an array, and I want to create 2 differents variables from the same array but this variables must have different result. For example, an array of string : the first variable must contain this array, and the other variable must contains this values but sorted. But it's not working :

    var letters = ['b', 'c', 'a']; // datas

    const lettersUnsorted = letters;        // i want the array like the var "letters"
    const letterSorted = letters.sort();    // i want the array like the var "letters" but sorted

    console.log(letterSorted);    // OK => returns: ["a", "b", "c"]
    console.log(lettersUnsorted); // KO => returns: ["a", "b", "c"] instead of ['b', 'c', 'a']
nico38
  • 29
  • 6

3 Answers3

1

This is because the reference to the original letters array is maintained.

lettersUnsorted and letterSorted are both referencing to the letters variable. This is because letters is an array (which is technically an object), and in JavaScript, assigning another variable to it will result in assignment by reference (rather than assignment by value). Therefore, any operations or mutation to letters will result in both lettersUnsorted and letterSorted in having the same result as letters, due to the reference to letter.

You should create a shallow clone of the original letters array. This will allow you to safely carry out any mutation without affecting the other array. We can achieve this using ES6's spread syntax.

const letters = ['b', 'c', 'a']; 
const lettersClone = [...letters].sort();
    
console.log(letters);
console.log(lettersClone);
wentjun
  • 40,384
  • 10
  • 95
  • 107
1

You should make a copy the array first because sort() method modifies the original array. You can make the copy of the array using slice()

var letters = ['b', 'c', 'a']; 
const lettersUnsorted = letters;       
const letterSorted = letters.slice().sort();    //this line is changed
console.log(letterSorted);    
console.log(lettersUnsorted);
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

you can use concat also.

var letters = ['b', 'c', 'a'];
const lettersUnsorted = letters;
const letterssorted = ([].concat(letters)).sort();
Negi Rox
  • 3,828
  • 1
  • 11
  • 18