Skip to content
Advertisement

Order an array of objects based in other array values

Lets 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 in such a way they are 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 who do not have a corresponding orderItem to be at the end of the array, is there any way to do it?

Advertisement

Answer

Well you can do it using Array.filter() and Array.some() method simply. Array.filter() method will return an array of the products matching with the item in orderItems whereas Array.some() method will simple check or match if element exists.

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 }];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 }];

const orderItems = [
{ order: 1, productId: 012},
{ order: 2, productId: 765 }, 
{ order: 3, productId: 123 }];
let OrderItem = [];
OrderItem = Products.filter((item,key)=>{
    return orderItems[key] && orderItems[key]['productId'] && Products.some((ele)=> ele.id === orderItems[key]['productId'])
    console.log(OrderItem)

})
Advertisement