views:

67

answers:

3

My code:

var company=new Array("Kestrel Moon:","BB:");
var basicPri=new Array(1165,1231);

for(var i=0;i<15;i++){
var companyTotal=company[i].concat(basicPri[…

document.write(""+companyTotal+"")

It shows on the screen:

Kestrel Moon: 1165

BB: 1231

I want to sort the array so that it goes ascending order of highest value of price so it should display it as:

BB: 1231
Kestrel Moon: 1165

A normal sort would not do it as it would sort the prices but the company names stay where they are, how do I sort both arrays so it would display what I want to display?

Thank You

A: 

typically, you would group the name with number:

function sortNumber(a,b)
{
    return b[1] - a[1];  // comparing using 2nd element
}

var n = [["ccc", 10.23], ["www", 23.12], ["mmm", 0.56]];
document.write(n.sort(sortNumber));

output:

www,23.12,ccc,10.23,mmm,0.56

and if you use jQuery, you can create a table from the result:

function sortNumber(a,b)
{
    return b[1] - a[1];  // comparing using 2nd element
}

var n = [["ccc", 10.23], ["www", 23.12], ["mmm", 0.56]];
sorted = n.sort(sortNumber);

$('body').append('<table id="thetable"></table>');
$('#thetable').css({borderCollapse: 'collapse'})
for (i = 0; i < sorted.length; i++) {
    $('#thetable').append('<tr><td>' + sorted[i][0] + '</td><td>' + sorted[i][1] + '</td></tr>')
}
$('td').css({ border: '1px solid #ccc', padding: '0.2em 1em' });
動靜能量
A: 

A normal sort would not do it as it would sort the prices but the company names stay where they are ...

In this case, an array of objects would probably be a better data structure for your data. Consider the example below:

var dict = [
  {company: 'Kestrel Moon:', basicPri: '1165'},
  {company: 'BB:', basicPri: '1231'}
];

var sorted = dict.sort(function(a, b) {
  return a.company.localeCompare(b.company);
});

console.log(sorted[0].company + ' ' + sorted[0].basicPri);
console.log(sorted[1].company + ' ' + sorted[1].basicPri);

// Prints:
// ------------------
// BB: 1231
// Kestrel Moon: 1165
Daniel Vassallo
A: 

Here's a possibility using your code as base (i.e. 2 arrays):

// comparaison functor
function sorter(a, b) {
    return a.name.localeCompare(b.name);
}

// build a sorted array of object like
// [ { "name": "foo", price: 123 }, ... ]
// sorted by company name (Locale aware order)
function mysort(comp, prices) {
    var res = [];

    for (var i = 0; i < comp.length; i++) {
        res.push({"name": comp[i], "price": prices[i]});
    }

    return res.sort(sorter);
}

var company = ["Kestrel Moon:", "BB:"];
var basicPri = [1165, 1231];
var companyTotal = "";
var arr = mysort(company, basicPri);

for (var i in arr) {
    companyTotal += arr[i].name + " " + arr[i].price + "<br/>";
}

document.write(companyTotal);

Tested on chrome 6.0.427.0 dev

RC