Je suis nouveau sur JavaScript. Je suis actuellement à obj avec des fonctions. J'ai ce code:Après avoir trié un tableau d'objets en JavaScript, comment afficher le mode de tri opposé? (mise à jour)
var tableIn = [
{name: "Alaska Thunderfuck", itemsBought: 15},
{name: "Courtney Act", itemsBought: 20},
{name: "Bianca del Rio", itemsBought: 13}
];
//going to use loops to limit input to specific words
var question1= prompt("By what to sort? type in : name or items bought").toLowerCase();
var question2= prompt("How to sort? up/down:").toLowerCase();
function myFunction(question1, question2) {
tableIn.sort(function sortingA(x,y) {
if (question2 == "up") {
if (question1 == "name") {
var ayy = x.name.toLowerCase();
var byy = y.name.toLowerCase();
if (ayy < byy) {return -1;}
if (ayy > byy) {return 1;}
return 0;
} else {
return x.itemsBought - y.itemsBought;
}
}
});
tableIn.sort(function sortingD(x,y) {
if (question2 == "down") {
return -1 * sortingA(x,y);
}
});
for (var idx = 0; idx < tableIn.length; idx++) {
console.log(tableIn[idx].name + tableIn[idx].itemsBought);
}
}
myFunction(question1, question2);
Comment puis-je obtenir le deuxième travail partiel? l'option inverse
Ouais! Vous auriez toujours pu faire une boucle inverse. pour '(var idx = tableIn.length - 1; idx> = 0; idx -)'. Bien que vous auriez pu le trier correctement en premier lieu. –