Ordenación de matrices de JavaScript


Tabla de contenido

    Mostrar tabla de contenidos


Ordenar una matriz

El método sort() ordena una matriz alfabéticamente:

Ejemplo

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>The sort() method sorts an array alphabetically:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;

fruits.sort();
document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>

Invertir una matriz

El método reverse() invierte los elementos de una matriz.

Puedes usarlo para ordenar una matriz en orden descendente:

Ejemplo

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>Sort in Reverse</h2>

<p>The reverse() method reverses the elements in an array.</p>
<p>By combining sort() and reverse() you can sort an array in descending order:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
// Create and display an array:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;

// First sort the array
fruits.sort();

// Then reverse it:
fruits.reverse();

document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>

Orden numérico

De forma predeterminada, la función sort() ordena los valores como cadenas.

Esto funciona bien para cadenas ("Apple" viene antes de "Banana").

Sin embargo, si los números se ordenan como cadenas, "25" es mayor que "100", porque "2" es mayor que "1".

Debido a esto, el método sort() producirá un resultado incorrecto al ordenar números.

Puedes solucionar este problema proporcionando una función de comparación:

Ejemplo

const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>Sort the array in ascending order:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo1").innerHTML = points;  

points.sort(function(a, b){return a - b});
document.getElementById("demo2").innerHTML = points;
</script>

</body>
</html>

Utilice el mismo truco para ordenar una matriz de forma descendente:

Ejemplo

const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>Sort the array in descending order:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo1").innerHTML = points;

points.sort(function(a, b){return b - a});
document.getElementById("demo2").innerHTML = points;
</script>

</body>
</html>



La función de comparación

El propósito de la función de comparación es definir un tipo alternativo orden.

La función de comparación debe devolver un valor negativo, cero o positivo, dependiendo de los argumentos:

function(a, b){return a - b}

Cuando la función sort() compara dos valores, envía los valores al función de comparación y ordena los valores según el valor devuelto (negativo, valor cero, positivo).

Si el resultado es negativo, a se ordena antes b.

Si el resultado es positivo, se ordena b antes de a.

Si el resultado es 0, no se realizan cambios en el orden de clasificación de los dos. valores.

Ejemplo:

La función de comparación compara todos los valores de la matriz, dos valores a la vez tiempo (a, b).

Al comparar 40 y 100, el método sort() llama a la función de comparación (40, 100).

La función calcula 40 - 100 (a - b), y Dado que el resultado es negativo (-60), la función de clasificación clasificará 40 como un valor inferior a 100.

Puede utilizar este fragmento de código para experimentar numéricamente y ordenar alfabéticamente:

<button onclick="myFunction1()">Sort Alphabetically</button>
<button 
 onclick="myFunction2()">Sort Numerically</button>
<p id="demo"></p>
 
<script>
const points = [40, 100, 1, 5, 25, 10];
 document.getElementById("demo").innerHTML = points;
function 
 myFunction1() {
  points.sort();
  document.getElementById("demo").innerHTML 
 = points;
}
function myFunction2() {
  points.sort(function(a, b){return 
 a - b});
  document.getElementById("demo").innerHTML = points;
}
 </script>

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>Click the buttons to sort the array alphabetically or numerically.</p>

<button onclick="myFunction1()">Sort Alphabetically</button>
<button onclick="myFunction2()">Sort Numerically</button>

<p id="demo"></p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;  

function myFunction1() {
  points.sort();
  document.getElementById("demo").innerHTML = points;
}
function myFunction2() {
  points.sort(function(a, b){return a - b});
  document.getElementById("demo").innerHTML = points;
}
</script>

</body>
</html>

Ordenar una matriz en orden aleatorio

Ejemplo

const points = [40, 100, 1, 5, 25, 10];
points.sort(function(){return 0.5 - Math.random()});

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>Click the button (again and again) to sort the array in random order.</p>

<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;  

function myFunction() {
  points.sort(function(){return 0.5 - Math.random()});
  document.getElementById("demo").innerHTML = points;
}
</script>

</body>
</html>

El método Fisher Yates

El ejemplo anterior, array.sort(), no es exacto. Favorecerá a algunos números sobre los demás.

El método correcto más popular se llama barajado de Fisher Yates y fue ¡Introducido en la ciencia de datos ya en 1938!

En JavaScript el método se puede traducir a esto:

Ejemplo

const points = [40, 100, 1, 5, 25, 10];

for (let i = points.length -1; i > 0; i--) {
  let j = Math.floor(Math.random() * (i+1));
  let k = points[i];
  
  points[i] = points[j];
  points[j] = k;
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Array Sort</h1>
<h2>The Fisher Yates Method</h2>

<p>Click the button (again and again) to sort the array in random order.</p>

<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;  

function myFunction() {
  for (let i = points.length -1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i+1));
    let k = points[i];
    points[i] = points[j];
    points[j] = k;
  }
  document.getElementById("demo").innerHTML = points;
}
</script>

</body>
</html>

Encuentre el valor de matriz más bajo (o más alto)

No hay funciones integradas para encontrar el máximo o el mínimo valor en una matriz.

Sin embargo, después de haber ordenado una matriz, puede utilizar el índice para obtener los valores más altos y más bajos.

Orden ascendente:

Ejemplo

const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
// now points[0] contains the lowest value
// and points[points.length-1] contains the highest value

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>The lowest number is <span id="demo"></span>.</p>

<script>
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
document.getElementById("demo").innerHTML = points[0];
</script>

</body>
</html>

Ordenación descendente:

Ejemplo

const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
// now points[0] contains the highest value
// and points[points.length-1] contains the lowest value

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>The highest number is <span id="demo"></span>.</p>

<script>
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
document.getElementById("demo").innerHTML = points[0];
</script>

</body>
</html>

Ordenar una matriz completa es un método muy ineficiente si solo desea encontrar el valor más alto (o más bajo).


Usando Math.max() en una matriz

Puedes usar Math.max.apply para encontrar el número más alto en una matriz:

Ejemplo

function myArrayMax(arr) {
    return Math.max.apply(null, arr);
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Array Sort</h1>

<p>The highest number is <span id="demo"></span>.</p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = myArrayMax(points);

function myArrayMax(arr) {
  return Math.max.apply(null, arr);
}
</script>

</body>
</html>

Math.max.apply(null, [1, 2, 3]) es equivalente a Math.max(1, 2 , 3).


Usando Math.min() en una matriz

Puedes usar Math.min.apply para encontrar el número más bajo en una matriz:

Ejemplo

function myArrayMin(arr) {
  return Math.min.apply(null, arr);
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Array Sort</h1>

<p>The lowest number is <span id="demo"></span>.</p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = myArrayMin(points);

function myArrayMin(arr) {
  return Math.min.apply(null, arr);
}
</script>

</body>
</html>

Math.min.apply(null, [1, 2, 3]) es equivalente a Math.min(1, 2 , 3).


Mis métodos JavaScript mínimos y máximos

La solución más rápida es utilizar un método "casero".

Esta función recorre una matriz comparando cada valor con el más alto valor encontrado:

Ejemplo (buscar máx.)

function myArrayMax(arr) {
  let len = arr.length;
  let max = -Infinity;
  while (len--) {
        
  if (arr[len] > max) {
      
  max = arr[len];
    }
  }
  return max;
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array Sort</h2>
<p>The highest number is <span id="demo"></span>.</p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = myArrayMax(points);

function myArrayMax(arr) {
  let len = arr.length;
  let max = -Infinity;
  while (len--) {
    if (arr[len] > max) {
      max = arr[len];
    }
  }
  return max;
}
</script>

</body>
</html>

Esta función recorre una matriz comparando cada valor con el más bajo valor encontrado:

Ejemplo (buscar mínimo)

 function myArrayMin(arr) {
  let len = arr.length;
  let min = Infinity;
  while (len--) {
    
  if (arr[len] < min) {
      
  min = arr[len];
    }
  }
  return min;
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array Sort</h2>
<p>The lowest number is <span id="demo"></span>.</p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = myArrayMin(points);

function myArrayMin(arr) {
  let len = arr.length;
  let min = Infinity;
  while (len--) {
    if (arr[len] < min) {
      min = arr[len];
    }
  }
  return min;
}
</script>

</body>
</html>


Ordenar matrices de objetos

Las matrices de JavaScript suelen contener objetos:

Ejemplo

const cars = [
  
 {type:"Volvo", year:2016},
  
 {type:"Saab", year:2001},
  
 {type:"BMW", year:2010}
];

Incluso si los objetos tienen propiedades de diferentes tipos de datos, el método sort() se puede utilizar para ordenar la matriz.

La solución es escribir una función de comparación para comparar los valores de las propiedades:

Ejemplo

cars.sort(function(a, b){return a.year - b.year});

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>Sort car objects on age:</p>

<p id="demo"></p>

<script>
const cars = [
  {type:"Volvo", year:2016},
  {type:"Saab", year:2001},
  {type:"BMW", year:2010}
];

displayCars();

cars.sort(function(a, b){return a.year - b.year});
displayCars();

function displayCars() {
  document.getElementById("demo").innerHTML =
  cars[0].type + " " + cars[0].year + "<br>" +
  cars[1].type + " " + cars[1].year + "<br>" +
  cars[2].type + " " + cars[2].year;
}
</script>

</body>
</html>

Comparar propiedades de cadenas es un poco más complejo:

Ejemplo

cars.sort(function(a, b){
  let x = a.type.toLowerCase();
  let y = b.type.toLowerCase();
    if (x < y) {return -1;}
  
 if (x > y) {return 1;}
  return 0;
});

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>Click the buttons to sort car objects on type.</p>

<button onclick="myFunction()">Sort</button>
<p id="demo"></p>

<script>
const cars = [
  {type:"Volvo", year:2016},
  {type:"Saab", year:2001},
  {type:"BMW", year:2010}
];

displayCars();

function myFunction() {
  cars.sort(function(a, b){
    let x = a.type.toLowerCase();
    let y = b.type.toLowerCase();
    if (x < y) {return -1;}
    if (x > y) {return 1;}
    return 0;
  });
  displayCars();
}

function displayCars() {
  document.getElementById("demo").innerHTML =
  cars[0].type + " " + cars[0].year + "<br>" +
  cars[1].type + " " + cars[1].year + "<br>" +
  cars[2].type + " " + cars[2].year;
}
</script>

</body>
</html>

Matriz estable sort()

ES2019 revisó el método Array sort().

Antes de 2019, la especificación permitía algoritmos de clasificación inestables como QuickSort.

Después de ES2019, los navegadores deben utilizar un algoritmo de clasificación estable:

Al ordenar elementos según un valor, los elementos deben mantener su posición relativa con respecto a otros elementos con el mismo valor.

Ejemplo

const myArr = [
  {name:"X00",price:100 },
  {name:"X01",price:100 },
  {name:"X02",price:100 },
  {name:"X03",price:100 },
  {name:"X04",price:110 },
  {name:"X05",price:110 },
  {name:"X06",price:110 },
  {name:"X07",price:110 }
];

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Stable Sort</h1>

<p>From ES2019, browsers must use a stable sorting algorithm.</p>
<p>When sorting elements on a key, the elements must keep their relative position to other objects with the same key.</p>

<p id="demo"></p>

<script>

const myArr = [
  {name:"X00",price:100 },
  {name:"X01",price:100 },
  {name:"X02",price:100 },
  {name:"X03",price:100 },
  {name:"X04",price:110 },
  {name:"X05",price:110 },
  {name:"X06",price:110 },
  {name:"X07",price:110 },
  {name:"X08",price:120 },
  {name:"X09",price:120 },
  {name:"X10",price:120 },
  {name:"X11",price:120 },
  {name:"X12",price:130 },
  {name:"X13",price:130 },
  {name:"X14",price:130 },
  {name:"X15",price:130 },
  {name:"X16",price:140 },
  {name:"X17",price:140 },
  {name:"X18",price:140 },
  {name:"X19",price:140 }
];

myArr.sort( (p1, p2) => {
  if (p1.price < p2.price) return -1;
  if (p1.price > p2.price) return 1;
  return 0;
});

let txt = "";
myArr.forEach(myFunction);

function myFunction(value) {
  txt += value.name + " " + value.price + "<br>"; 
}
document.getElementById("demo").innerHTML = txt;
</script>

</body>
</html>

En el ejemplo anterior, al ordenar por precio, no se permite que el resultado salga con los nombres en otra posición relativa como esta:

X01 100
X03 100
X00 100
X03 100
X05 110
X04 110
X06 110
X07 110

Referencia de matriz completa

Para obtener una referencia completa de Array, vaya a nuestro:

Referencia completa de matrices de JavaScript.

La referencia contiene descripciones y ejemplos de todos los Array. propiedades y métodos.