Remove duplicates from array in typescript

Viewed 795

I am new to typescript, and i've been having some problems in using my javascript skills. For example, can someone help me to write this exactly same javascript code below in typescript?

If not possible at all, any typescript function that will render the expected output (array without duplicate values).

This is just a simple way to remove duplicates from an array, but seems like typescript doesn't let me define an empty object... I'm not sure...

The output of the code below is: ['John', 'Paul', 'George', 'Ringo']

Thanks!

const names = ['John', 'Paul', 'George', 'Ringo', 'John'];

function removeDups(names) {
  let unique = {};
  names.forEach(function(i) {
    if(!unique[i]) {
      unique[i] = true;
    }
  });
  return Object.keys(unique);
}

removeDups(names)

2 Answers

In this case, you just have to add types

const names = ['John', 'Paul', 'George', 'Ringo', 'John'];

function removeDups(names: string[]) {
  let unique: any = {};
  names.forEach(function(i: string) {
    if(!unique[i]) {
      unique[i] = true;
    }
  });
  return Object.keys(unique);
}

removeDups(names)

typescript playground

names = ['John', 'Paul', 'George', 'Ringo', 'John']; 

removeDups(names) {
 let unique = {};
  this.names.forEach((i) => {
    if(!unique[i]) {
      unique[i] = true;
    }
  });
  return Object.keys(unique);
}

Then call removeDups from where you want

Here is another way:

names = ['John', 'Paul', 'George', 'Ringo', 'John']; 

removeDups(names) {

  return this.names.filter((elem, index, self)=> {
    return index === self.indexOf(elem);
})
}
Related