Почему это
function compareSold(num1, num2) {
return num1.sold - num2.sold;
}
здесь
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
var products = [ { name: "Grapefruit", calories: 170, color: "red", sold: 8200 },
{ name: "Orange", calories: 160, color: "orange", sold: 12101 },
{ name: "Cola", calories: 210, color: "caramel", sold: 25412 },
{ name: "Diet Cola", calories: 0, color: "caramel", sold: 43922 },
{ name: "Lemon", calories: 200, color: "clear", sold: 14983 },
{ name: "Raspberry", calories: 180, color: "pink", sold: 9427 },
{ name: "Root Beer", calories: 200, color: "caramel", sold: 9909 },
{ name: "Water", calories: 0, color: "clear", sold: 62123 }
];
function compareSold(num1, num2) {
return num1.sold - num2.sold;
}
function printProducts(products) {
for (var i = 0; i < products.length; i++) {
console.log("Name: " + products[i].name +
", Calories: " + products[i].calories +
", Color: " + products[i].color +
", Sold: " + products[i].sold);
}
}
products.sort(compareSold);
printProducts(products);
</script>
</head>
<body>
</body>
</html>
работает нормально, а здесь
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
var products = [ { name: "Grapefruit", calories: 170, color: "red", sold: 8200 },
{ name: "Orange", calories: 160, color: "orange", sold: 12101 },
{ name: "Cola", calories: 210, color: "caramel", sold: 25412 },
{ name: "Diet Cola", calories: 0, color: "caramel", sold: 43922 },
{ name: "Lemon", calories: 200, color: "clear", sold: 14983 },
{ name: "Raspberry", calories: 180, color: "pink", sold: 9427 },
{ name: "Root Beer", calories: 200, color: "caramel", sold: 9909 },
{ name: "Water", calories: 0, color: "clear", sold: 62123 }
];
function compareName(num1, num2) {
return num1.name - num2.name;
}
function compareCalories(colaA, colaB) {
if (colaA.calories > colaB.calories) {
return 1;
} else if (colaA.calories === colaB.calories) {
return 0;
} else {
return -1;
}
}
function compareColor(colaA, colaB) {
if (colaA.color > colaB.color) {
return 1;
} else if (colaA.color === colaB.color) {
return 0;
} else {
return -1;
}
}
function printProducts(products) {
for (var i = 0; i < products.length; i++) {
console.log("Name: " + products[i].name +
", Calories: " + products[i].calories +
", Color: " + products[i].color +
", Sold: " + products[i].sold);
}
}
products.sort(compareName);
console.log("Products sorted by name:");
printProducts(products);
products.sort(compareCalories);
console.log("Products sorted by calories:");
printProducts(products);
products.sort(compareColor);
console.log("Products sorted by color:");
printProducts(products);
</script>
</head>
<body>
</body>
</html>
Я даже всякие консол логи удалял, лишь бы всё заработало...