Tri des tableaux JavaScript


Table des matières

    Afficher la table des matières


Trier un tableau

La méthode sort() trie un tableau par ordre alphabétique :

Exemple

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

Essayez-le vous-même →

<!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>

Inverser un tableau

La méthode reverse() inverse les éléments d'un tableau.

Vous pouvez l'utiliser pour trier un tableau par ordre décroissant :

Exemple

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

Essayez-le vous-même →

<!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>

Tri numérique

Par défaut, la fonction sort() trie les valeurs sous forme de chaînes.

Cela fonctionne bien pour les chaînes ("Apple" vient avant "Banana").

Cependant, si les nombres sont triés sous forme de chaînes, "25" est supérieur à "100", parce que "2" est plus grand que "1".

Pour cette raison, la méthode sort() produira un résultat incorrect lors du tri. Nombres.

Vous pouvez résoudre ce problème en fournissant une fonction de comparaison :

Exemple

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

Essayez-le vous-même →

<!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>

Utilisez la même astuce pour trier un tableau par ordre décroissant :

Exemple

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

Essayez-le vous-même →

<!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 fonction de comparaison

Le but de la fonction comparer est de définir un tri alternatif commande.

La fonction de comparaison doit renvoyer une valeur négative, nulle ou positive, selon les arguments:

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

Lorsque la fonction sort() compare deux valeurs, elle envoie les valeurs au compare la fonction et trie les valeurs en fonction du résultat (négatif, valeur zéro, positive).

Si le résultat est négatif, a est trié avant b.

Si le résultat est positif, b est trié avant a.

Si le résultat est 0, aucune modification n'est apportée à l'ordre de tri des deux valeurs.

Exemple :

La fonction compare compare toutes les valeurs du tableau, deux valeurs à la fois heure (a, b).

Lors de la comparaison de 40 et 100, la méthode sort() appelle la fonction de comparaison(40, 100).

La fonction calcule 40 - 100 (a - b), et le résultat étant négatif (-60), la fonction de tri triera 40 comme une valeur inférieure à 100.

Vous pouvez utiliser cet extrait de code pour expérimenter numériquement et tri alphabétique :

<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>

Essayez-le vous-même →

<!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>

Trier un tableau dans un ordre aléatoire

Exemple

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

Essayez-le vous-même →

<!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>

La méthode Fisher Yates

L'exemple ci-dessus, array.sort(), n'est pas exact. Cela favorisera certains nombres par rapport aux autres.

La méthode correcte la plus populaire s'appelle le mélange Fisher Yates et a été introduit dans la science des données dès 1938 !

En JavaScript, la méthode peut être traduite comme suit :

Exemple

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;
}

Essayez-le vous-même →

<!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>

Trouver la valeur de tableau la plus basse (ou la plus élevée)

Il n'y a pas de fonctions intégrées pour trouver le maximum ou le minimum valeur dans un tableau.

Cependant, après avoir trié un tableau, vous pouvez utiliser la commande index pour obtenir les valeurs les plus élevées et les plus basses.

Tri croissant :

Exemple

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

Essayez-le vous-même →

<!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>

Tri décroissant :

Exemple

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

Essayez-le vous-même →

<!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>

Le tri d'un tableau entier est une méthode très inefficace si vous souhaitez uniquement trouver la valeur la plus élevée (ou la plus basse).


Utiliser Math.max() sur un tableau

Vous pouvez utiliser Math.max.apply pour trouver le nombre le plus élevé dans un tableau :

Exemple

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

Essayez-le vous-même →

<!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]) est équivalent à Math.max(1, 2 , 3).


Utiliser Math.min() sur un tableau

Vous pouvez utiliser Math.min.apply pour trouver le nombre le plus bas d'un tableau :

Exemple

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

Essayez-le vous-même →

<!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]) est équivalent à Math.min(1, 2 , 3).


Mes méthodes JavaScript Min/Max

La solution la plus rapide est d'utiliser une méthode "fait maison".

Cette fonction parcourt un tableau en comparant chaque valeur avec la plus élevée valeur trouvée :

Exemple (Trouver Max)

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

Essayez-le vous-même →

<!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>

Cette fonction parcourt un tableau en comparant chaque valeur avec la valeur la plus basse valeur trouvée :

Exemple (Trouver Min)

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

Essayez-le vous-même →

<!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>


Tri des tableaux d'objets

Les tableaux JavaScript contiennent souvent des objets :

Exemple

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

Même si les objets ont des propriétés de types de données différents, la méthode sort() peut être utilisé pour trier le tableau.

La solution consiste à écrire une fonction de comparaison pour comparer les valeurs des propriétés :

Exemple

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

Essayez-le vous-même →

<!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>

La comparaison des propriétés de chaîne est un peu plus complexe :

Exemple

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;
});

Essayez-le vous-même →

<!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>

Tableau stable sort()

ES2019 révisé la méthode Array sort().

Avant 2019, la spécification autorisait des algorithmes de tri instables tels que QuickSort.

Après ES2019, les navigateurs doivent utiliser un algorithme de tri stable :

Lors du tri d'éléments sur une valeur, les éléments doivent conserver leur position relative par rapport aux autres éléments ayant la même valeur.

Exemple

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 }
];

Essayez-le vous-même →

<!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>

Dans l'exemple ci-dessus, lors du tri par prix, le résultat ne permet pas de sortir avec les noms dans une autre position relative comme celle-ci :

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

Référence complète du tableau

Pour une référence complète sur Array, accédez à notre :

Référence complète du tableau JavaScript.

La référence contient des descriptions et des exemples de tous les Array propriétés et méthodes.