J'essaie de faire le tri des ordres ascendants à plusieurs niveaux pour un tableau ci-dessous d'objets.
p> sortById(array, key) {
return array.sort(function(a, b) {
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
3 Réponses :
Vous pouvez p> trier code> avec plusieurs conditions ou code> conditions: var array = [{id: 1, color: 'red', objname: 'tomato'},{id: 1, color: 'orange', objname: 'pumpkin'},{id: 2, color: 'red', objname: 'tomato' },{id: 1, color: 'red', objname: 'cherry' },{id: 1, color: 'orange', objname: 'sunset'}];
var resultArray = array.sort((a,b)=>{
return a.id-b.id || a.color.localeCompare(b.color) || a.objname.localeCompare(b.objname)
});
console.log(resultArray);
Vous pouvez adopter une approche dynamique en collectant les clés recherchées et en utilisant Array # Certains code> avec un court-circuit pour Truthy valeurs.
p> .as-console-wrapper { max-height: 100% !important; top: 0; }
Vous pouvez essayer quelque chose comme ça.