2

I have two dependent dropdown lists the first list getting the services from array1 and the second filtering a list from array2 based on the results of list 1.

This works as it should in this fiddle: jsfiddle

The issue is the 2nd value has values that are separated with a comma. I need to separate those then check against all the other values in value 2 and only display one instance.

i.e.

"Banner (Premium)", "Banner (Premium), Banner (440gsm)", "Banner (550gsm)"

Would be

"Banner (Premium)", "Banner (440gsm)", "Banner (550gsm)"

Here's my code:

function menu2() {
var serviceValue = document.getElementById("service-type").value;
 var el = document.getElementById("media-type");
 var newArray = media.filter(function(r) {return r[1].includes(serviceValue)})
 var currentlyAdded = [];
 el.innerHTML = "";
 newArray.forEach(function(r) {
 if(currentlyAdded.indexOf(r[1]) === -1) {
 var option = document.createElement('option');
  option.text = r[1];
  el.appendChild(option);
  currentlyAdded.push(r[1]);
  }
 })

}

I believe I need to use .split and .concat but I can't work out how to add it to my script.

2 Answers 2

2

You can use a Set to create an array with unique values.

const str = `Banner (Premium), Banner (Premium), Banner (440gsm)`
const splitted = [...new Set(str.split(`, `))];
console.log(splitted);

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

2 Comments

Thanks, I've tried your code and although it works, I can't get it working with my script.
Hi @Juan-man, I think that has more to do with the nature of your code. It seems a bit overcomplicated ... check this jsFiddle, or this one for alternatives
0

A solution with split

const str = '"Banner (Premium)", "Banner (Premium), Banner (440gsm)", "Banner (550gsm)"'


// desired "Banner (Premium)", "Banner (440gsm)", "Banner (550gsm)"

const desired = str.split('"').filter(x => /[A-Z][a-z]/.test(x)).map( x => {
  const splitted = x.split(',');
  return (splitted.length < 2)?splitted[0]:splitted[1];
});



console.log(desired)

I believe that looking for csv you would find pure regex solutions

2 Comments

Thanks, I've tried for the last 2 hours 2 implement this into my jsfiddle to the get the results I need but I'm having no luck. split is not a function.
Glad you solved it with the other answer. If the first split fails it might be because it's not a string but directly an array. Then you only need the code from the .map on

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.