Create Product Sort System using JavaScript [duplicate] - javascript

This question already has answers here:
Sorting an array of objects by property values
(35 answers)
Closed 19 days ago.
How would I be able to create a product sort system using JavaScript
I have this Array:
let products = [
{
productName: "Product1",
price: 40
},
{
productName: "Product2",
price: 50
},
{
productName: "Product3",
price: 20
},
{
productName: "Product4",
price: 10
},
{
productName: "Product5",
price: 10
},
{
multiple other products with prices
},
];
I want to sort the products by price, so that the products with the lowest price are shown at the top of the page, and the products with the highest price are shown at the bottom of the page. How would I do this?

You can pass a callback to Array#sort that subtracts the prices.
let products=[{productName:"Product1",price:40},{productName:"Product2",price:50},{productName:"Product3",price:20},{productName:"Product4",price:10},{productName:"Product5",price:10},];
products.sort((a, b) => a.price - b.price);
console.log(products);

Related

Create Pagination in JavaScript with an Array using the slice method

How would I be able to create pagination in JavaScript using the slice method.
I have this Array:
let products = {
data: [
{
productName: "Product1",
},
{
productName: "Product2",
},
{
productName: "Product3",
},
{
productName: "Product4",
},
{
productName: "Product5",
},
{
multiple other products
},
],
};
I have looped through all of the products and displayed them on screen like this:
for (let i of products.data) {
let card = document.createElement("div");
let name = document.createElement("h5");
container.appendChild(name);
card.appendChild(container);
document.getElementById("products").appendChild(card);
}
I now want to create pagination. Each page should include a maximum of 10 products. I want to do this using the slice method.
I also want to create buttons on my website, which will be used for the pagination. The buttons should look similar to this.
How would I be able to create pagination in JavaScript using the slice method.
Example of how the pagination buttons should look

Check arrays to find equal id

I have a list of products like:
listOfProducts = [{name: "prod1", productId: 1}, {name:"prod2", productId: 2},.....]
If I choose a product i'll populate the array
listSelectedProducts
it will contains the choosen products.
And I make a post to save my choise.
Now If I go back in the products page, i'll have an array:
oldProductsArray
which contains the products that I have saved in db.
listSelectedProducts
with my selected products.
Now If I remove the selected product to choose another one, my oldProductsArray will have the first product, but listSelectedProducts will have the new product choose.
So now I should remove from my db the product that I don't want anymore (an it is in oldProductsArray). So I thought to compare (and there I have my problem) the two arrays and if elements in oldProductsArray are not in listSelectedProducts, i'll create a new array with the products not selected to delete them.
So let's do an example:
I'm in my products page and choose a product.
So listSelectedProducts = [{name: "prod1", productId: 1}]
and I will post in db.
I return in products page and this time I have:
listSelectedProducts = [{name: "prod1", productId: 1}]
oldProductsArray = [{name: "prod1", productId: 1}]
I deselect the product: prod1 and choose the product: prod2
So I have:
listSelectedProducts = [{name: "prod2", productId: 2}]
oldProductsArray = [{name: "prod1", productId: 1}]
and now I should check if products in oldProductsArray are also in listSelectedProducts, if they are I can do the post, if they are not (like in this case) I should remove from db the product.
So I have a function:
this.checkOldProduct(oldProductsArray, listSelectedProducts)
in this function:
checkOldProduct(oldProductsArray, listSelectedProducts){
let arrayProductToDelete = []
// i have tried like this, but it doesn't work properly.
listSelectedProducts.filter(p1 => !oldProducts.some(p2 => { p1.productId === p2.productId, arrayProductToDelete.push(p2) }));
}
I hope I have expressed myself well, in any case I am ready to add clarifications. thank you
some quick consideration first:
If that's really all the data you have for the product list, you should probably just use a PUT method on your API and simply replace the whole list without having to compute the difference
If you still somehow need to make separate operations to update products list, I guess you should make POST requests to add new items, DELETE requests to delete items and PATCH requests to update single items (like same id but different quantities?)
From the point above: do you also have quantities for items?
Question Specific Answer
So based solely on your question I think easiest way is to find the list of items to delete something like this:
const removedItems = oldArray.filter((old) => !newArray.find((_new) => old.id === _new.id));
And request their deletion.
Full Diff Answer
If you want to compute a full diff of your chart items so you can make multiple update requests, you could do something like this:
function arrayDiff(oldArray, newArray) {
const addedAndUpdatedItems = newArray.reduce((diff, item, index, array) => {
const oldItem = oldArray.find((old) => old.id === item.id);
if(!oldItem) {
diff.added.push(item);
} else if(oldItem.quantity !== item.quantity) {
diff.updated.push(item);
}
return diff;
}, {
added: [],
updated: []
});
const removedItems = oldArray.filter((old) => !newArray.find((_new) => old.id === _new.id));
return {
...addedAndUpdatedItems,
removed: removedItems
}
}
const oldArray = [{ name: "prod1", id: 1, quantity: 1 }, { name: "prod3", id: 3, quantity: 4 }];
const newArray = [{ name: "prod1", id: 1, quantity: 3 }, { name: "prod2", id: 2, quantity: 3 }];
const diff = arrayDiff(oldArray, newArray);
console.log({ diff });
Output is
{
"added": [
{
"name": "prod2",
"id": 2,
"quantity": 3
}
],
"updated": [
{
"name": "prod1",
"id": 1,
"quantity": 3
}
],
"removed": [
{
"name": "prod3",
"id": 3,
"quantity": 4
}
]
}
If you want do find matching objects in both array using their productId,
Here is my solution
First get the productId list from one array then you can easily filter the another array using includes() method
let listSelectedProducts = [{name: "prod2", productId: 1}, {name: "prod2", productId: 2}, {name: "prod2", productId: 3}]
let oldProductsArray = [{name: "prod1", productId: 1}, {name: "prod1", productId: 2}]
let oldIds = oldProductsArray.map(d=>d.productId)
let arrayProductToDelete = listSelectedProducts.filter(d=>oldIds.includes(d.productId))
console.log(arrayProductToDelete)

Javascript Sort Array of objects by object property that exists in several objects [duplicate]

This question already has answers here:
Sort an array of object by a property (with custom order, not alphabetically)
(7 answers)
Closed last year.
I have an array of products where several products can have the same color, and i want to be able to sort this array by the color value. How i would i achieve an Array sorting for example to display all products first that has the color property of "red"? Or any other color that i will tell the array to sort first by.
const arr = [
{
name: "T-shirt",
color: "red",
price: 20
},
{
name: "Shoes",
color: "yellow",
price: 20
},
{
name: "Pants",
color: "red",
price: 20
},
{
name: "Cap",
color: "yellow",
price: 20
},
{
name: "Skirt",
color: "red",
price: 15
},
]
Like this you will sort your array by color, if you want to get the yellow color in first return 1 and red return 2 to have in position 2 etc:
const getRanking = (ele) => {
if (ele.color == "red") return 2;
if (ele.color == "yellow") return 1;
};
arr.sort((a,b) => getRanking(a) - getRanking(b))

Find within array of objects the item having maximum value of certain property and return another property of that item [duplicate]

This question already has answers here:
From an array of objects, how to return property `b` of the object that has the highest property `a`?
(4 answers)
Finding the max value of an attribute in an array of objects
(21 answers)
Closed 2 years ago.
Trying to create a function to return the Name if the price is the highest using javascript. Still learning.
{
Name: "Effective Yoga Habits",
type: "book",
price: 10.99
},
{
Name: "Yoga kit",
type: "product",
price: 199.99
},
{
Name: "Medative surroundings",
type: "CD",
price: 6.00
}
]
If anyone can help I would appreciate it. Thank you in advance
You may use Array.prototype.reduce() to traverse your array and have accumulator to store the record with greatest price value:
const src = [{Name:"Effective Yoga Habits",type:"book",price:10.99},{Name:"Yoga kit",type:"product",price:199.99},{Name:"Medative surroundings",type:"CD",price:6.00}],
result = src
.reduce((r, {Name,price}) =>
price > r.price ? {Name,price} : r)
.Name
console.log(result)

Flatten JavaScript Object [duplicate]

This question already has answers here:
Converting a JS object to an array using jQuery
(18 answers)
Closed 6 years ago.
On my realtime firebase database I store my products with unique keys, i.e.,
- products
|
- KPYGghMerx_AKU8b4ki
|
- name: "product A"
- price: 1.99
- KPYNtki7UWnh5evYQgjT
|
- name: "product B"
- price: 3.99
I retrieve this data as follows
this.productsRef.on('value', (snapshot) => {
var data = snapshot.val();
}
This returns the object as expected, i.e.,
{
KPYGghMerx_AKU8b4ki: {
name: "product A"
price: 1.99
},
KPYNtki7UWnh5evYQgjT: {
name: "product B"
price: 3.99
}
}
What's the easiest way to map these objects into an array without the unique keys? e.g.
{
name: "product A"
price: 1.99
},
{
name: "product B"
price: 3.99
}
Object.values will extract the values from an object and return it as an array:
Object.values({ k1: v1, k2: v2 }); //[v1, v2]
If you need to polyfill it you can write a simple values function:
function values(obj) {
return Object.keys(obj).map(function (key) {
return obj[key];
});
}

Categories