Nick Lewis

Javascript - Removing duplicates in an array

Recently I came across a situation where this was necessary. The data being pulled in from the API contained a lot of duplicates.

6 Aug, 2022 ยท 1 min read

Recently I came across a situation where this was necessary. The data being pulled in from the API contained a lot of duplicates. So to give you an example:

[{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 1, name: 'one'}]

There are two items in the above array that are the same, my data was worse than this with many duplicates, so came up with the function that looked like this:

const arr = [{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 1, name: 'one'}]

const ids = arr.map(o => o.id)
const filtered = arr.filter(({id}, index) => !ids.includes(id, index + 1))

console.log(filtered)

This can be adapted as needed but it would return, a reduced array with just one of each item, not multiple copies of them.

Spread the word with everyone on Twitter
Tweet this post
Powered by Webmentions

You may also like to read ๐Ÿ“–

VueJS - Removing dead code from your VueJS project

23 Aug, 2022 ยท 1 min read

VueJS - Removing dead code from your VueJS project

Deep Selectors in Vue

9 Sep, 2022 ยท 1 min read

Deep Selectors in Vue