0

I would like to know how to remove repeated name property in array of objects

using javascript/typescript

Tried 
var result = itemList1.filter((v,i,a)=>a.findIndex(v2=>(v2.name===v.name))===i)

var itemList1 = [
  {id:1, name: 'anu'},
  {id:2, name: 'john'},
  {id:3, name: 'john'}
]
Expected Result:
 [
  {id:1, name: 'anu'},
  {id:2, name: 'john'}
]

Codelearn
  • 31
  • 5
  • https://stackoverflow.com/questions/2218999/how-to-remove-all-duplicates-from-an-array-of-objects – Teemu Apr 18 '23 at 06:09

1 Answers1

0

I am not sure exactly what the problem is, but the following line of code will help you remove the duplicated values by name in your array. Your code works for that, but I hope you placed the filtering after defining the array, but anyway here is the piece of code written a bit more formatted.

.filter(
    (value, index, self) =>
        index === self.findIndex((t) => t.name === value.name)
)

Here is the filter documentation and here is the findIndex documentation.

And here is a snippet:

var itemList1 = [
    { id: 1, name: 'anu' },
    { id: 2, name: 'john' },
    { id: 3, name: 'john' }
];

const filtered = itemList1.filter(
    (value, index, self) =>
        index === self.findIndex((t) => t.name === value.name)
)

console.log(filtered);

As a suggestion, always format your code because that way it becomes easier to read for you and other people.

robert
  • 73
  • 7