0

I am trying to add functionality into my JS script that de-duplicates the values returned. My original script here:

try{
var productList = dataLayer.basket.products.map(function(product) {
    return product.travelType;
});

return productList.join('|');
  }
catch(err){}

which returns values from an array like Bus|Bus|Train|Car|Bus

What I am trying to get to is an additional part of the script that would clean those values and de-duplicate them. For example the above script would only show "bus" once e.g. Bus|Train|Car

I have tried to do this using a filter but I am getting a null value being returned:

try{
var productList = dataLayer.basket.products.map(function(product) {
    return product.travelType;
});
  
var filteredArray = productList.filter(function(item, pos){
    return productList.indexOf(item)=== pos;
  });
  
return filteredArray.join('|');
  }
catch(err){}

Any guidance would be gratefully appreciated.

Thanks, M

user3411489
  • 17
  • 1
  • 5

5 Answers5

1

To filter duplicates in an array:

const array = ['toto', 'tata', 'tutu', 'toto'];
const filteredArray = [...new Set(array)];

console.log(filteredArray);
Leo
  • 741
  • 6
  • 14
0

const remove_duplicates = (arr) => {
    let setArr = new Set(arr);
    let values = setArr.values();
    return Array.from(values);
}
const example = ['Bus', 'Bus', 'Car', 'Bike'];

console.log(remove_duplicates(example).join('|'));
Nicolae Maties
  • 2,476
  • 1
  • 16
  • 26
0

I think the top answer in this question is just what you're searching for. Just apply that to your productList and it should get rid of all duplicate values.

Edit: oops, I just saw you were already doing exaclty that. But your code should work that way, I just tried it out in the console and it worked just as expected. The null values must be caused by some other part of your program.

peabrainiac
  • 998
  • 9
  • 16
0

Your code is fine as is, the error must be in your data or in another part of your code that you didn't post:

const dataLayer = {
  basket:{products:[
      {travelType:'a'},
      {travelType:'b'},
      {travelType:'c'},
      {travelType:'b'},
      {travelType:'c'},
      {travelType:'a'},

  ]}
}

var productList = dataLayer.basket.products.map(function(product) {
  return product.travelType;
});
  
var filteredArray = productList.filter(function(item, pos){
  return productList.indexOf(item)=== pos;
});
  
console.log(filteredArray.join('|'));
HMR
  • 37,593
  • 24
  • 91
  • 160
0

Using modern javascript:

let arr = ['Bus', 'Bus', 'Train', 'Car', 'Bus'];
let filteredArr= [... new Set(arr)]; 
let result = filteredArr.join('|');
Bassem Mamar
  • 328
  • 2
  • 14