Jquery remove all options from select list except some specific

Solution:1

You can try this code:

const optionsValuesToKeep = $('input[type="hidden"]').val().split(','); // is ['3325','3326','3323','3322']
$('#datetime_0_cars > option').filter( // jQuery filter not vanilla-JS filter
    (index,optionElement) => !optionsValuesToKeep.includes(optionElement.value)
).remove();

It splits the hidden input’s value attribute into an array, gets all options, filters out options that should be kept, and removes the rest.

Solution:2

I would do this by first hiding all options:

$("select option").hide();

and after that show the options I want. For instance, if you want number 3118, you do:

$("select option[value=3118]").show();

Solution:3

In the following example, a select box with 4 options is created. On button click, all the options are removed and one new option is added.

<!DOCTYPE html>
<html>
  <head>
    <script src=
   </script>
 
    <!-- Basic inline styling -->
    <style>
      body {
        text-align: center;
      }
      h1 {
        color: green;
        font-size: 40px;
      }
      p {
        font-size: 25px;
        font-weight: bold;
      }
      button {
        display: block;
        cursor: pointer;
        margin: 5rem auto 0 auto;
      }
      select {
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <h1>GeeksforGeeks</h1>
    <p>
       jQuery - Remove all options of select box 
       then add one option and select it
    </p>
 
    <select id="geek-select">
      <option value="geek1">GEEK 1</option>
      <option value="geek2">GEEK 2</option>
      <option value="geek3">GEEK 3</option>
      <option value="geek4">GEEK 4</option>
    </select>
    <button onclick="removeThenAdd()">
      Click me to remove all options and then add one option
    </button>
    <script type="text/javascript">
      function removeThenAdd() {      
        $("#geek-select").find("option").remove().end().append(
        '<option value = "gfg">GeeksForGeeks</option>');
      }
    </script>
  </body>
</html>