Instagram | Twitter | LinkedIn
What is the output of the following code: A, B or C?
Click here to see the correct answer and explanation 👀
Correct Answer | Explanation |
---|---|
B | The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. For our case, note that 10 is before 2 in the result array, because 10 is before 2 depending on the position of the Unicode value. |
Explanation based on 👉🏼 Array.prototype.sort() | MDN
Code:
(function() {
const numbers = [1, 10, 2, 21];
numbers.sort();
console.log(numbers);
})();
¿Qué imprime el siguiente código: A, B o C?
Haz click aquí para ver la respuesta correcta y su explicación 👀
Respuesta correcta | Explicación |
---|---|
B | El método sort() ordena los elementos de un arreglo (array) localmente y devuelve el arreglo ordenado. La ordenación no es necesariamente estable. El modo de ordenación por defecto responde a la posición del valor del string de acuerdo a su valor Unicode. Para nuestro caso, ten en cuenta que 10 está antes que 2 en el array resultante, porque 10 está antes que 2 según la posición del valor Unicode. |
Explicación basada en 👉🏼 Array.prototype.sort() | MDN
Código:
(function() {
const numbers = [1, 10, 2, 21];
numbers.sort();
console.log(numbers);
})();
B