1

I am trying to refactor some code to use the javascript filter function to get rid of objects that have identical properties.

schemas = schemas.filter((schema, index, newArray) => {
            return index === schemas.findIndex(obj => obj.className == schema.className)
        })

schemas is an array of a custom object NameSchema:

interface NameSchema {
    schemaId: string;
    className: string;
}

I have two problems with using the findIndex method, the compiler complains that findIndex doesn't exist on NameSchema, and that many objects in the array have identical properties, but aren't identical objects.

How do I use the Array.filter function to get a list of objects that don't have objects that don't have identical classNames?

Edit

I found my answer here: Remove duplicates from an array of objects in JavaScript

It ends up looking like this for my code:

schemas = schemas.filter((schema, index, self) => index === self.findIndex((obj) => (obj.className === schema.className)))
Justin
  • 154
  • 1
  • 17
  • 1
    You could convert it to a Set which will automatically remove all duplicates.If you dont want to do that you want to use reduce not filter. – GifCo Mar 26 '19 at 19:56

2 Answers2

8

Does this help?

const array = [
  {id: 1, val: 'hello 1a'},
  {id: 1, val: 'hello 1b'},
  {id: 2, val: 'hello 2a'},
  {id: 2, val: 'hello 2b'},
]

const filteredArray = array.filter((obj, index, arr) => {
        return arr.map(mapObj => mapObj.id).indexOf(obj.id) === index;
 });

console.log(filteredArray)
Conturbo
  • 106
  • 3
0

You should use a Set - it automatically removes all duplicates. If you need an array, turn it back into an array:

schemas = [...new Set(schemas)];
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79