I have a couple of parallel arrays called names and sales. I have the user enter up to 100 salespeople (names, obviously) and their sales. I have no problem printing these to a table. The catch (for me, anyway) is that they need to be sorted in descending order according to sales. I have made a function called sort
which is coded (poorly - as I am just beginning to learn JavaScript) as:
function sort(names, sales) {
var i = 0;
var j = 0;
var temp = 0;
for (var i = 0; i < sales.length - 1; i++) {
var min = i;
for (var j = i + 1; j < array.length; j++)
if (sales[j] < (sales[min])) min = j;
temp = sales[i];
sales[i] = sales[min];
sales[min] = temp;
temp = names[i];
names[i] = names[min];
names[min] = temp;
}
}
I am in need of some help here, obviously. Can anyone lend a hand to point out the (no doubt numerous) errors?
We have been instructed to write our own sort. Sales and names are input thro开发者_运维知识库ugh two different functions (getName()
and getSales()
) using prompts.
First, why not use a single two-dimensional array, say, SalesArray, for example:
[ ['someName', 'someSale'], ['someName2', 'someSale2'], ]
Next, simply inspect SalesArray[i][1] while sorting.
As for sorting, try implementing bubblesort, especially if you're new to sorting algorithms.
Why not just store both the name and sales in a single object? Then everything is in one array.
// Declare array
var people = new Array();
// Somewhere in a loop to add people...
var person = {
name: "jdmichal",
sales: 1000
};
people.push(person);
// Now sort based on the sales property in each object.
精彩评论