Skip to content
Advertisement

Order an array of objects based in other array values

Lets say I have an array of products:

JavaScript

and I have another, smaller array where I store the order of the products on my page:

JavaScript

And I want my Products array in such a way they are ordered like the orderItems array defines, like so:

JavaScript

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.

JavaScript
Advertisement