Home > Net >  Split array by unique items with some items comma separated using javascript
Split array by unique items with some items comma separated using javascript

Time:02-24

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.

CodePudding user response:

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);

CodePudding user response:

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

  • Related