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

时间:2017-05-24 09:00:27

标签: javascript arrays

我需要对我的数组进行排序,但由于我有两个对象,我不知道该怎么做。我需要按字母顺序和玩具编号按升序对狗名称进行排序。我怎样才能做到这一点?

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

1 个答案:

答案 0 :(得分:0)

您可以使用Array#sort所需的排序功能进行自定义排序,然后按name排序,然后按toynum排序

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

在使用数据填充数组后,您只需要排序一次。

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>