Как настроить сортировку сайта по цене от наибольшей до наименьшей - PullRequest
0 голосов
/ 29 мая 2020

Я работаю над веб-сайтом небольшого продуктового магазина, используя javascript, и у меня возникают проблемы с сортировкой товаров в категории продуктов от наименее дорогих до самых дорогих.

Покупатель выбирает «клиента» категория и выбирает спецификацию своего аллергена, после выбора спецификации они должны выбрать вкладку продуктов, где они увидят список продуктов, как показано на снимке экрана .

Как вы можете видеть , цены на товары перепутались, как я могу сделать так, чтобы товары go от самого дешевого товара до самого дорогого товара внизу.

Код ниже:

//groceries.js
// Array of products, each product is an object with different fieldset
// A set of ingredients should be added to products		 

var products = [
	{
		name: "brocoli $1.99",
		vegetarian: true,
		glutenFree: true,
		price: 1.99,
		organic:true
	},
	{
		name: "bread $2.35",
		vegetarian: true,
		glutenFree: false,
		price: 2.35,
		organic:false

	},
	{
		name: "salmon $10.00",
		vegetarian: false,
		glutenFree: true,
		price: 10.00,
		organic:true

	},

	{
		name: "chicken $8.99",
		vegetarian: false,
		glutenFree: true,
		price: 8.99,
		organic:true

	},

	{
		name: "macaroni $2.99",
		vegetarian: false,
		glutenFree: false,
		price: 2.99,
		organic:true

	},

	{
		name: "cake mix $3.99",
		vegetarian: false,
		glutenFree: false,
		price: 3.99,
		organic:true

	},

	{
		name: "Jam $4.99",
		vegetarian: true,
		glutenFree: true,
		price: 4.99,
		organic:true

	},

	{
		name: "banana $1.99",
		vegetarian: true,
		glutenFree: true,
		price: 1.99,
		organic:true

	},

	{
		name: "eggs $1.50",
		vegetarian: true,
		glutenFree: true,
		price: 1.50,
		organic:true

	},

	
	{
		name: "apples $2.49",
		vegetarian: true,
		glutenFree: true,
		price: 2.49,
		organic:true
	}

];
	


// given restrictions provided, make a reduced list of products
// prices should be included in this list, as well as a sort based on price

function restrictListProducts(prods, restriction) {
	let product_names = [];
	for (let i=0; i<prods.length; i+=1) {

		
		if ((restriction == "Vegetarian") && (prods[i].vegetarian == true)){
			product_names.push(prods[i].name);
		}
		else if ((restriction == "Gluten Free") && (prods[i].glutenFree == true)){
			product_names.push(prods[i].name);
		}

		else if((restriction == "GlutenFreeandVegetarian") && (prods[i].glutenFree == true) && (prods[i].vegetarian == true) ){
			product_names.push(prods[i].name);
		}

		else if((restriction == "Organic") && (prods[i].organic == true) ){
			product_names.push(prods[i].name);
		}

		else if((restriction == "GlutenFreeandOrganic") && (prods[i].organic == true) && (prods[i].glutenFree == true) ){
			product_names.push(prods[i].name);
		}

		else if((restriction == "GlutenFreeandVegetarian") && (prods[i].vegetarian == true) && (prods[i].glutenFree == true) ){
			product_names.push(prods[i].name);
		}

		else if((restriction == "GlutenFreeandVegetarianandOrganic") && (prods[i].organic == true) && (prods[i].vegetarian == true) && (prods[i].glutenFree == true) ){
			product_names.push(prods[i].name);
		}

		else if (restriction == "None"){
			product_names.push(prods[i].name);
		}
	
	}
	return product_names;
}

// Calculate the total price of items, with received parameter being a list of products
function getTotalPrice(chosenProducts) {
	totalPrice = 0;
	for (let i=0; i<products.length; i+=1) {
		if (chosenProducts.indexOf(products[i].name) > -1){
			totalPrice += products[i].price;
		}
	}
	return totalPrice;
}






// main.js

function openInfo(evt, tabName) {

	// Get all elements with class="tabcontent" and hide them
	tabcontent = document.getElementsByClassName("tabcontent");
	for (i = 0; i < tabcontent.length; i++) {
		tabcontent[i].style.display = "none";
	}

	// Get all elements with class="tablinks" and remove the class "active"
	tablinks = document.getElementsByClassName("tablinks");
	for (i = 0; i < tablinks.length; i++) {
		tablinks[i].className = tablinks[i].className.replace(" active", "");
	}

	// Show the current tab, and add an "active" class to the button that opened the tab
	document.getElementById(tabName).style.display = "block";
	evt.currentTarget.className += " active";

}


	
// generate a checkbox list from a list of products
// it makes each product name as the label for the checkbos

function populateListProductChoices(slct1, slct2) {
    var s1 = document.getElementById(slct1);
    var s2 = document.getElementById(slct2);
	
	// s2 represents the <div> in the Products tab, which shows the product list, so we first set it empty
    s2.innerHTML = "";
		
	// obtain a reduced list of products based on restrictions
    var optionArray = restrictListProducts(products, s1.value);

	// for each item in the array, create a checkbox element, each containing information such as:
	// <input type="checkbox" name="product" value="Bread">
	// <label for="Bread">Bread/label><br>
		
	for (i = 0; i < optionArray.length; i++) {
			
		var productName = optionArray[i];
		// create the checkbox and add in HTML DOM
		var checkbox = document.createElement("input");
		checkbox.type = "checkbox";
		checkbox.name = "product";
		checkbox.value = productName;
		s2.appendChild(checkbox);
		
		// create a label for the checkbox, and also add in HTML DOM
		var label = document.createElement('label')
		label.htmlFor = productName;
		label.appendChild(document.createTextNode(productName));
		s2.appendChild(label);
		
		// create a breakline node and add in HTML DOM
		s2.appendChild(document.createElement("br"));    
	}
}
	
// This function is called when the "Add selected items to cart" button in clicked
// The purpose is to build the HTML to be displayed (a Paragraph) 
// We build a paragraph to contain the list of selected items, and the total price

function selectedItems(){
	
	var ele = document.getElementsByName("product");
	var chosenProducts = [];
	
	var c = document.getElementById('displayCart');
	c.innerHTML = "";
	
	// build list of selected item
	var para = document.createElement("P");
	para.innerHTML = "You selected : ";
	para.appendChild(document.createElement("br"));
	for (i = 0; i < ele.length; i++) { 
		if (ele[i].checked) {
			para.appendChild(document.createTextNode(ele[i].value));
			para.appendChild(document.createElement("br"));
			chosenProducts.push(ele[i].value);
		}
	}
		
	// add paragraph and total price
	c.appendChild(para);
	c.appendChild(document.createTextNode("Total Price is " + getTotalPrice(chosenProducts)));
		
}
/* This style sheet is taken from  https://www.w3schools.com/howto/howto_js_tabs.asp> */

/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons that are used to open the tab content */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}
<!DOCTYPE html>
<html>
<head>
	<! This style sheet is taken from  https://www.w3schools.com/howto/howto_js_tabs.asp>
	<link href="styles/style.css" rel="stylesheet" type="text/css">
</head>

<h1>Super Groceries</h1>

<body>

<!-- Tab links, each one with an onclick event associated with it -->
<div class="tab">
  <button class="tablinks" onclick="openInfo(event, 'Client')">Client</button>
  <button class="tablinks" onclick="openInfo(event, 'Products')">Products</button>
  <button class="tablinks" onclick="openInfo(event, 'Cart')">Cart</button>
</div>

<!-- Tab content -->
<div id="Client" class="tabcontent">
  <h3>Client Information</h3>
  <p>Tell us a bit about you.</p>
	Choose a Category:
	<select id="dietSelect" name="dietSelect" onchange="populateListProductChoices(this.id, 'displayProduct')">
	<option value=""></option>
	<option value="Vegetarian">Vegetarian</option>
    <option value="Gluten Free">GlutenFree</option>
    <option value="Organic"> Organic</option>
    <option value="GlutenFreeandVegetarian"> GlutenFreeandVegetarian</option>
    <option value="GlutenFreeandOrganic"> GlutenFreeandOrganic</option>
    <option value="VegetarianandOrganic"> VegetarianandOrganic</option>
    <option value="GlutenFreeandVegetarianandOrganic"> GlutenFreeandVegetarianandOrganic</option>



    <option value="None">None</option>
  </select>
  
 
</div>

<div id="Products" class="tabcontent">
  <h3>Your targeted products</h3>
  <p>We preselected products based on your restrictions.</p>
	 Choose items to buy:
	 <div id="displayProduct"></div>
	 <button id="addCart" type="button" class="block" onclick="selectedItems()">
		Add selected items to cart.
	</button>
</div>

<div id="Cart" class="tabcontent">
  <h3>Cart</h3>
  <p>Here is your cart.</p>
  <div id="displayCart"></div>
</div>

<script src="scripts/groceries.js"></script>
<script src="scripts/main.js"></script>

</body>
</html>

Спасибо

Ответы [ 2 ]

2 голосов
/ 29 мая 2020

Я сделал новый массив цен на товары (вы также можете решить, не создавая новый массив, но я решил его, чтобы решение было более понятным) и отсортировал его от низкой к высокой цене:

var priceProducts = new Array(products.length);
for (let i = 0; i < priceProducts.length; i++) {
  priceProducts[i] = products[i].price;

}
priceProducts.sort(((x, y) => x - y));

for (let i = 0; i < priceProducts.length; i++) {
    console.log(priceProducts[i]);
}

Вывод:

1.5
1.99
2.35
2.49
2.99
3.99
4.99
8.99
10
1 голос
/ 29 мая 2020

Вы можете использовать метод sort (), чтобы решить эту проблему. Например:

var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);

Для получения дополнительной информации используйте эту ссылку

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...