1

I'm currently removing duplicates from a dropdown menu using the following script, but I now need to try to remove all duplicates apart from the LAST option to enable the search criteria to be remembered by Solspace's Freeform.

Does anyone cleverer than me know how to adjust the script to remove all duplicates APART from the last one?

// REMOVE DUPLICATES FROM LOCATION DROPDOWN
var optionValues =[];
$('#locationList option').each(function(){
   if($.inArray(this.value, optionValues) >-1){
      $(this).remove()
   }else{
      optionValues.push(this.value);
   }
});

Thanks in advance,

Tom

2
  • Do you mean the last option on the list or the last occurrence of each duplicate? Commented Aug 26, 2016 at 12:46
  • Sorry if I wasn't clear, I need to leave only the last occurrence of each duplicate Commented Aug 30, 2016 at 9:16

2 Answers 2

1
$(document).ready(function() {
  var optionValues = [];
  var lastRemoved = null;
  $('#locationList option').each(function(){
     if($.inArray(this.value, optionValues) >-1){
        $(this).remove();
        // remember the very last removed one
        lastRemoved = $(this);
     }else{
        optionValues.push(this.value);
     }
  });

  // after removing duplicates, add the very last removed one back to the list
  $('#locationList').append(lastRemoved);
});

Assuming I understood your problem correctly, this will remove all the duplicates from the list excluding the very last occurrence. Let me know if that helps!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that appears to be doing the trick although that does raise another question about why the select option is not being selected, even though the 'selected' parameter is being added?
0

Not sure if this is what you are trying to do:

var optionValues = [];
var optionItems  = $('locationList option');

optionItems.each(function (index) {
    if (index > optionItems.length - 1) {
        return;
    }
    if ($.inArray(this.value, optionValues) > -1) {
        $(this).remove();
    } else {
        optionValues.push(this.value);
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.