Get the closest & highest id using javascript

i have two lists one for products to select and the other for the selected products i want to be able to return the selected product to its original place.

I kinda solve it in the following format but the issue is it might be hundreds of products

$(document).on('click', "#remove_product", function () {
    var product = $(this).parents("li"),
        found = false;
    $('.products_list li').each(function() {
        if(this.id > product.attr('id') && !found ){
            product.clone().insertBefore(this); 
            found = true;
        }
    });
    if(!found) product.clone().append(".products_list");
    product.remove();
})
.products_list button{
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="products_list">
  <li id="1">Content 1</li>
  <li id="2">Content 2</li>
  <li id="4">Content 4</li>
  <li id="5">Content 5</li>
</ul>

<hr>

<ul class="selected_products">

  <li id="3">
    Content 3
    <button id="remove_product">remove product</button>
  </li>

</ul>

Any better solution?

Answer

The simplest way to achieve your goal would be to create a function which sorts the li elements within the ul based on their id. You can then call this function whenever an update is made to the li.

The function can also be made generic enough to work for both ul containers, when adding/removing an item from each.

Note in the example below that I added the button element to each li by default, as per your pattern of hiding them through CSS for the initial list. I also changed the id on the button to a class, as id need to be unique.

With that said, try this:

let $productsList = $('.products_list');
let $selectedList = $('.selected_products');
let sortProductsInContainer = $container => $container.find('li').sort((a, b) => a.id > b.id ? 1 : -1).appendTo($container);

// add product to selected list
$productsList.on('click', 'li', e => {
  $(e.target).closest('li').appendTo($selectedList);
  sortProductsInContainer($selectedList);
});

// remove product from selected list
$selectedList.on('click', ".remove_product", e => {
  $(e.target).closest("li").appendTo($productsList);
  sortProductsInContainer($productsList);
})
.products_list button {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="products_list">
  <li id="1">Content 1 <button class="remove_product">remove product</button></li>
  <li id="2">Content 2 <button class="remove_product">remove product</button></li>
  <li id="4">Content 4 <button class="remove_product">remove product</button></li>
  <li id="5">Content 5 <button class="remove_product">remove product</button></li>
</ul>

<hr>

<ul class="selected_products">
  <li id="3">Content 3 <button class="remove_product">remove product</button></li>
</ul>