3

I have the following map function to strip each element in the object of their commas if it exists.

var items = ['mum, dad', 'uncle, dad', 'brother, sister'];
var clean = [];
clean = items.filter(function(item) {
  return item.split(',');
});

The problem is that I don't get the expected outcome. My clean output is the same as items output. It should be like:

console.log(items) //  ['mum, dad', 'uncle, dad', 'brother, sister']
console.log(clean) //  ['mum', dad', 'uncle', dad', 'brother', sister']

there is also another point, how can I get the unique values only, as you can see, once they are stipped of their commas, some values are repeated, like dad, how can I keep only one?

Bonnard
  • 389
  • 2
  • 8
  • 26

3 Answers3

6

You can use map() instead of filter and ES6 Set to return only unique elements.

var items = ['mum, dad', 'uncle, dad', 'brother, sister'];
var clean = [...new Set([].concat(...items.map(e => e.split(', '))))]

console.log(clean)

For IE and other older versions of browsers you can use this solution.

var items = ['mum, dad', 'uncle, dad', 'brother, sister'];
var clean = [].concat.apply([], items.map(function(e) {
  return e.split(', ');
})).filter(function(e) {
  return !this[e] ? this[e] = 1 : false;
}, {})

console.log(clean)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • this is very nice, but i get an error in IE browser! could you give the equivalent in normal javascript supported by IE please? – Bonnard Aug 09 '17 at 11:09
2

Filter only return those elements which have value true for that particular function. If you want to do some operation/manipulation on each item, then you have to go for map. Try to be as simple as possible, you just have to map each element, split it, and then append it into array clean. Lets have a look at this simple piece of code.

function uniqueArray2(arr) {
    var a = [];
    for (var i=0, l=arr.length; i<l; i++)
        if (a.indexOf(arr[i]) === -1 && arr[i] !== '')
            a.push(arr[i]);
    return a;
}
var items = ['mum, dad', 'uncle, dad', 'brother, sister'];
var clean = [];
items.map(function(item) {
  var splitArray = item.split(',');
  for(var i=0; i<splitArray.length; i++){
    clean.push(splitArray[i]);
  }
});
clean = uniqueArray2(clean);
console.log (clean)
Abdullah Danyal
  • 1,106
  • 1
  • 9
  • 25
0

You are using filter instead of map.

Using map will return you an array of arrays. If ES6 isn't an option, you can merge it into a single array and remove duplicates like this:

var items = ['mum, dad', 'uncle, dad', 'brother, sister'];
var clean = [];
clean = items.filter(function(item) {
 return item.split(',');
});
var merged = [].concat.apply([], clean);
var unique = arr.filter(function(elem, index, self) {
  return index == self.indexOf(elem);
})
urielSilva
  • 400
  • 1
  • 11