2017-10-19 4 views
-2

j'ai les éléments suivants tableau Javascript:tableau tri JS de tableaux

myArr = [[["One"],["First","Fourth","Third"]], 
     [["Two"],["First","Second","Third"]], 
     [["Three"],["First","Third"]], 
     [["One two"],["Fourth","Second","Third"]], 
     [["One three"],["Fourth","Third"]], 
     [["One two three"],["Second","Third"]]]; 

je besoin de ce tri si je reçois:

[[["One"],["First","Fourth","Third"]], 
[["One three"],["Fourth","Third"]], 
[["One two"],["Fourth","Second","Third"]], 
[["One two three"],["Second","Third"]], 
[["Three"],["First","Third"]], 
[["Two"],["First","Second","Third"]]] 

Je suppose que je pouvais utiliser myArr.sort() et obtenir le tableau correctement trié . Il fonctionne sur un tableau plat mais pas sur des tableaux imbriqués. Quand j'utilise myArr.sort() je reçois:

[[["One three"],["Fourth","Third"]], 
[["One two three"],["Second","Third"]], 
[["One two"],["Fourth","Second","Third"]], 
[["One"],["First","Fourth","Third"]], 
[["Three"],["First","Third"]], 
[["Two"],["First","Second","Third"]]] 

Cela me semble zéro sens. Comment le tri JS parvient-il à ce résultat? Et comment puis-je obtenir le résultat dont j'ai besoin.

+1

Donnez la documentation essayer. Cela aura du sens. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – nilobarp

+2

_ "les éléments sont triés en les convertissant en chaînes et en comparant les chaînes dans l'ordre des points de code Unicode" _. Les tableaux sont convertis en chaînes délimitées par des virgules. Comme l'espace précède la virgule dans la séquence Unicode, les éléments avec des mots séparés par des espaces viennent en premier. – david25272

+0

@ david25272 merci. C'est probablement l'explication la plus claire que j'ai lue. – bos570

Répondre

3

laid chemin:

myArr.sort((a, b) => (a[0][0]).localeCompare(b[0][0])) 

Fondamentalement, vous voulez comparer le premier élément de chaque tableau à l'autre de

myArr = [[["One"],["First","Fourth","Third"]], 
 
     [["Two"],["First","Second","Third"]], 
 
     [["Three"],["First","Third"]], 
 
     [["One two"],["Fourth","Second","Third"]], 
 
     [["One three"],["Fourth","Third"]], 
 
     [["One two three"],["Second","Third"]]]; 
 
      
 
const sorted = myArr.sort((a, b) => (a[0][0]).localeCompare(b[0][0])); 
 

 
console.log(sorted);