0

I have a javascript array that looks like this:

["polyester", "cotton", "Polyester, Nylon", "Cotton, Acrylic", "Polyester, fiber", "nylon, Leather"]

I would like to mutate this array into this:

["polyester", "cotton", "Nylon", "Acrylic", "fiber", "Leather"]

That is split the strings with commas inside the array and then remove the duplicates while ignoring the case sensitivity. I have looked at other questions on SO. They either explain how to remove duplicates from an array or how to split a single string on commas and not many strings inside an array. I have tried to solve it by:

mutated = a.filter(function(item, pos) {
 return a.indexOf(item) == pos;
})

but this does not split the comma seperated strings with in the array. I am seeking for a solution that will do both splitting and removing duplicates while ignoring case sensitivity.

Optimus Pette
  • 3,250
  • 3
  • 29
  • 50

1 Answers1

2

Here's a simple solution. It does not preserve the original upper case items, but I don't see a reason to do that, since it's based only on the order in the original array.

// we join the original items to a long string, then split it up
var items = original.join (',').split (/\s*,\s*/);

// we make all items lowercase uniformly
items = items.map (function (item) {
  return item.toLowerCase ();
});

// we put new items in a unique list
var uniqueItems = [];
items.forEach (function (item) {
  if (uniqueItems.indexOf (item) < 0) {
    uniqueItems.push (item);
  }
});
Márton Tamás
  • 2,759
  • 1
  • 15
  • 19