TypeScript / JavaScript: Remove Duplicates from Object Array using filter and findIndex method

Let’s see how we can efficiently remove the duplicates from the object array.

Consider the following products array.

const products: Product[] = [
    { id: 1, name: 'Product 1', price: 100 },
    { id: 2, name: 'Product 2', price: 200 },
    { id: 3, name: 'Product 3', price: 300 },
    { id: 1, name: 'Product 1', price: 100 }
]

This products array contains one duplicate product.

{ id: 1, name: 'Product 1', price: 100 }

We can remove the duplicates from object array using filter and findIndex array methods as following.

const prods = products.filter((value, index, array) => index == array.findIndex(item => item.id == value.id));

console.table(prods);

Output

Array.prototype.filter()

Filter method returns new array which passes the filter criteria.

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

Array.prototype.findIndex()

findIndex returns the index of the first element that satisfies the conditions, else returns -1.

const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// expected output: 3

References:

Array.prototype.filter()

Array.prototype.findIndex()

Conclusion

In this post we learned how we can efficiently remove the duplicates from the object array.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s