So I have an array of objects with some meals.
example:
const meals = [
{
id: 1,
title: 'Strawberry Salad with Poppy Seed Dressing',
img: 'Strawberry-Salad-with-Poppy-Seed-Dressing.jpg',
book: 1,
calories: 298,
servings: 3,
type: 'lunch',
price: 15,
cook: 'Jenny Jefferson',
quantity: 10,
},
{
id: 2,
title: 'Cashew Turkey Salad Sandwiches',
img: 'turkey-sandwich.jpg',
book: 2,
calories: 198,
servings: 2,
type: 'lunch',
price: 9,
cook: 'Jenny Jefferson',
quantity: 10
}];
Now I need to be able to sort on id, title, img, book, calories, servings, type, price, cook, quality.
I'm doing this with a dropdown where i'm loading these items
function loadDropdownFilter() {
let sortby = document.querySelector("#sortby");
let i = 0;
let filterObj = Object.getOwnPropertyNames(meals[i]);
while (i < filterObj.length) {
sortby.innerHTML += `<option>${filterObj[i]}</option>`;
i++;
}
}
The code of my dropdown:
<label for="search">Search</label><input type="search" name="search" id="search"/>
<label>Sort items by
<select id="sortby" name="sortby">
</select>
</label>
<select id="direction" name="direction">
<option value="asc">ascending</option>
<option value="desc">descending</option>
</select>
</form>
<div id="mealList">
<div class="flexcontainer" id="fillMealList"></div>
</div>
I already made a new function to sort but i'm stuck in this.
The function
function sortByObject(){
let value = document.querySelector("#sortby");
let getValueOfObject = value.options[value.selectedIndex].text;
console.log(getValueOfObject);
meals.sort();
console.log(meals);
}
I tried to display these into my HTML but it doesn't work.
My code:
let sortValue = document.querySelector("#sortby").value;
console.log(sortValue);
meals.sort(function(a, b) {
if (a[sortValue] < b[sortValue]) {
return -1;
}
return 1;
});
console.log(meals);
let id = 1;
for (let i = 0; i < meals.length; i++) {
let item = meals.find(item => item.id === id);
document.querySelector("#fillMealList").innerHTML =
`<article class='createPopup'>
<h3>${item.title}</h3>
<figure>
<img src='images/${item.img}'>
<figcaption>
Meal by:<span>${item.cook}</span>
</figcaption>
</figure>
<div class='info'>
<p>€ <span>${item.price}</span>/pp</p>
<a href='javascript:addToCart(${item.id})' class='addToCart'>Order</a>
</div>
</article>`;
id++;
}