Today we discuss how in Magento 2 sort collection by give ids. Sometime we need to get product collection by given ids form example random ids 5,4,13. We take the example of product collection and filter it by give ids. You can use this on any kind of collection like order collection, category collection and any custom collection too. So here is our example.
public function __construct(
$this->_productCollectionFactory = $productFactory;
public function getProductCollection()
$productCollection = $this->_productCollectionFactory->create();
$productCollection->getSelect()->order(new \Zend_Db_Expr('FIELD(entity_id,' . implode(',', $productIds).')'));
Note: You can sort any collection following this example.