2017-10-20 25 views
0

我是JavaScript新手。我目前在功能obj。我有這樣的代碼:用JavaScript排序對象數組後,我將如何顯示相反的排序方式? (更新)

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

我怎樣才能獲得的第二部分工作?它的反向選項

+1

呀!你可以一直運行一個反向循環。爲'(var idx = tableIn.length - 1; idx> = 0; idx - )'。儘管你可以將它排在第一位。 –

回答

0

要顛倒排序陣列的順序,請使用Array#reverse - tableIn.revese()

要以相反的方向排序,請將sortAsc函數的結果乘以-1。

例如:

var question1 = "name"; 
 

 
function sortAsc(x, y) { 
 
    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; 
 
    } 
 
} 
 

 
function sortFunc(x, y) { 
 
    var factor = question2 == "up" ? 1 : -1; 
 
    return factor * sortAsc(x, y); 
 
} 
 

 
var tableIn = [ 
 
    {name: "Alaska Thunderfuck", itemsBought: 15}, 
 
    {name: "Courtney Act", itemsBought: 20}, 
 
    {name: "Bianca del Rio", itemsBought: 13} 
 
]; 
 

 
var question2 = "up"; 
 
console.log('sortAsc: ', tableIn.sort(sortFunc)); 
 

 
var question2 = "down"; 
 
console.log('sortDesc: ', tableIn.sort(sortFunc));

+0

但是對於降序我想「下」輸入。我在哪裏將if語句放在question2 ==「down」中? – AJH

+0

所以我在掙扎的是如果question2 ==「up」就得到升序,如果question2 ==「down」則降序。 我想解決** if if語句,但在您的版本中,我有需要的if語句是在sortAsc函數內 – AJH

+0

您需要從'sortAsc'中取出第一個'if'狀態,並使用它決定是否要乘以1或-1。查看更新的代碼。 –

0

嘗試改變 return x.itemsBought - y.itemsBought;

return (x.itemsBought - y.itemsBought) * -1;