简体   繁体   English

使用两个对象对数组进行排序

[英]Sorting array with two objects

I need to sort my array but since I have two objects in it I am not sure how to do this. 我需要对我的数组进行排序,但由于我有两个对象,我不知道该怎么做。 I need to sort dog names in alphabetical and toy number in ascending order. 我需要按字母顺序和玩具编号按升序对狗名称进行排序。 How can I do this? 我怎样才能做到这一点?

function start() {
    document.getElementById("task").innerHTML="Task 8";
    var arr = [];
    var vName = "";
    vName = prompt("Enter dog name (leave blank to stop)");
    vToyNum = prompt("Enter number of dog toys (leave blank to stop)");
    while (vName.length > 0 && vToyNum.length > 0) {
        arr.push({name:vName,toynum:vToyNum});
        arr.sort({name:vName});
        vName = prompt("Enter dog name (leave blank to stop)");
        vToyNum = prompt("Enter number of dog toys (leave blank to stop)");
    }
    var vOutput = "Dog names and No. of toys:" + displayDog(arr);
    var toyTot = 0;
    for (var val=0; val < arr.length; val++) {
        toyTot += Number (arr[val].toynum);
    }
    vOutput += "<br/><br/>Total number of toys: " + toyTot;
    document.getElementById("output").innerHTML= vOutput;
}

function displayDog(arr) {
    var vOutput = "";
    for (var val = 0; val < arr.length; val++) {
        vOutput += "<br/> Dog " + (val + 1) +" "+ arr[val].name
                + ", No. of toys " + arr[val].toynum;
    }
    return vOutput;
}

You could use a sort function as Array#sort requires for custom sorts and sort by name first and then by toynum 您可以使用排序函数作为Array#sort需要进行自定义排序,然后按name排序,然后按toynum

arr.sort(function (a, b) {
    return a.name.localeCompare(b.name) || a.toynum - b.toynum;
});

You need to sort only once after filling the array with data. 在使用数据填充数组后,您只需要排序一次。

 function start() { document.getElementById("task").innerHTML = "Task 8"; var arr = [], vName = "", vToyNum, vOutput, toyTot = 0, val, DOG_QUESTION = "Enter dog name (leave blank to stop)", TOY_QUESTION = "Enter number of dog toys (leave blank to stop)"; vName = prompt(DOG_QUESTION); vToyNum = prompt(TOY_QUESTION); while (vName.length > 0 && vToyNum.length > 0) { arr.push({ name: vName, toynum: vToyNum }); vName = prompt(DOG_QUESTION); vToyNum = prompt(TOY_QUESTION); } arr.sort(function (a, b) { return a.name.localeCompare(b.name) || a.toynum - b.toynum; }); vOutput = "Dog names and No. of toys:" + displayDog(arr); for (val = 0; val < arr.length; val++) { toyTot += Number(arr[val].toynum); } vOutput += "<br /><br />Total number of toys: " + toyTot; document.getElementById("output").innerHTML = vOutput; } function displayDog(arr) { var val, vOutput = ""; for (val = 0; val < arr.length; val++) { vOutput += "<br /> Dog " + (val + 1) + " " + arr[val].name + ", No. of toys " + arr[val].toynum; } return vOutput; } start(); 
 <div id="task"></div> <div id="output"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM