0
Failed to "save" array ordering
I created a code to sort an array and store its values in a second array, but when I sort it again it modifies the value assigned to the second array and instead of appearing:
Ordenamento Alfabético:
Chave 0 Valor 1
Chave 1 Valor 10
Chave 2 Valor 2
Chave 3 Valor 200
Chave 4 Valor 3
Ordenamento Numérico:
Chave 0 Valor 1
Chave 1 Valor 2
Chave 2 Valor 3
Chave 3 Valor 10
Chave 4 Valor 200
Appears:
Ordenamento Alfabético:
Chave 0 Valor 1
Chave 1 Valor 2
Chave 2 Valor 3
Chave 3 Valor 10
Chave 4 Valor 200
Ordenamento Numérico:
Chave 0 Valor 1
Chave 1 Valor 2
Chave 2 Valor 3
Chave 3 Valor 10
Chave 4 Valor 200
Can someone help me and tell me what I’m doing wrong?
// Variáveis
var matriz = [];
var novamatriz = [];
var i = 0;
// Principal
matriz = [1, 2, 10, 3, 200];
matriz.sort();
novamatriz[0] = matriz;
matriz.sort(function(a, b) {
return (a - b);
});
novamatriz[1] = matriz;
// Console
console.log("Ordenamento Alfabético: \n\n");
for (i = 0; i < novamatriz[0].length; i++) {
console.log("Chave " + i + " Valor " + novamatriz[0][i]);
}
console.log("\nOrdenamento Numérico: \n\n");
for (i = 0; i < novamatriz[1].length; i++) {
console.log("Chave " + i + " Valor " + novamatriz[0][i]);
}
when you copy an object matching, like this
novamatriz[0] = matriz;
you have two variables pointing to the same object, ie if change novamatrix or matrix will be changing the same thing. I suggest reading this answer, especially the difference in value and reference: https://answall.com/a/15260/57220– Ricardo Pontual