Useful Development

Typescript: filtering an array for distinct values

banner image
posted on Aug 27, 2019

The JavaScript Array object does not have a distinct method but the filter can be used to the same effect. An old StackBlitz code sample I wrote ages ago to remind myself how to do this seems to be the most popular thing I've ever done so I though I would clean it up a bit for the people who are using it. The approach to filtering duplicates is well established in JavaScript: use the filter method to only check if the index of the current item is equal to the first index of the item in the array and only add the item if it does.

  
    const arrayWithDuplicates = [1, 1, 2, 3, 4, 4, 4, 5, 1];
    const distinctArray = arrayWithDuplicates.filter((n, i) => arrayWithDuplicates.indexOf(n) === i);
    console.dir(distinctArray);
   // output: [1, 2, 3, 4, 5]
   
 

This will work for filtering objects as well as long as they are the same instance. If they are not, or if you want to filter by a specific property value use findIndex instead to match the objects.

  
    export class Thing {
      constructor(public id: number, public name: string) { }
    }

    const thingsWithDuplicates = [
      new Thing(1, 'red'),
      new Thing(2, 'yellow'),
      new Thing(3, 'green'),
      new Thing(4, 'blue'),
      new Thing(5, 'orange'),
      new Thing(2, 'yellow'),
      new Thing(3, 'green')
    ];

    const distinctThings = thingsWithDuplicates.filter(
      (thing, i, arr) => arr.findIndex(t => t.id === thing.id) === i
    );
   
 

If you need an Internet Explorer friendly version use indexOf with find instead.

  
    const distinctThings = thingsWithDuplicates.filter((thing, i, arr) => {
      return arr.indexOf(arr.find(t => t.id === thing.id)) === i;
    });
   
 

Here is the StackBlitz sample so you can see it in action: