Let's say I have an array of products:
const Products = [
{ id: 123, productName: "Portable Tabletop Game", quantity: 12 },
{ id: 456, productName: "Gift Card", quantity: 23 },
{ id: 789, productName: "Box of Chocolates", quantity: 8 },
{ id: 012, productName: "Gift Box", quantity: 4 },
{ id: 098, productName: "Balloons", quantity: 15 },
{ id: 765, productName: "Music Box", quantity: 30 }
];
and I have another, smaller array where I store the order of the products on my page:
const orderItems = [
{ order: 1, productId: 021 },
{ order: 2, productId: 765 },
{ order: 3, productId: 123 }
];
and I want my Products array items to be ordered like the orderItems array defines, like so:
const Products = [
{ id: 012, productName: "Gift Box", quantity: 4 },
{ id: 765, productName: "Music Box", quantity: 30 },
{ id: 123, productName: "Portable Tabletop Game", quantity: 12 },
{ id: 456, productName: "Gift Card", quantity: 23 },
{ id: 789, productName: "Box of Chocolates", quantity: 8 },
{ id: 098, productName: "Balloons", quantity: 15 }
];
and I want the products which do not have a corresponding orderItem to be at the end of the array.
Is there any way to do this?
orderItemsarray; based on your expected ordering, the first item'sproductIdshould be012, not021. Also JavaScript numbers with leading zeros are interpreted in octal rather than decimal, so you may want to use strings for ids instead. I addressed both of these in a section of my answer