Good
Good

Reputation: 81

Find objects that have duplicate names inside the array in JavaScript

I have an array that I find in the searchName section, and in the resultName section I separate the duplicate names, and in the filters section I want to display the objects that have those duplicate names in the console.log, but an empty array Please help me to get the answer

    const data = [
     {id: 1,name: "Liam",age: 20},
     {id: 1,name: "Noah",age: 22},
     {id: 1,name: "Liam",age: 20},
     {id: 1,name: "Elijah",age: 18},
     {id: 1,name: "Elijah",age: 18}
]
    const searchName = data.map(item => item.name)
    console.log(searchName);
    const toFindDuplicates = arry => arry.filter((item, index) => arry.indexOf(item) !== index);
    const resultName = toFindDuplicates(searchName)
    console.log(resultName);
    const filters = data.filter(x => x.Name === resultName)
    console.log(filters);

Upvotes: 1

Views: 97

Answers (3)

jabaa
jabaa

Reputation: 6743

First you can count the names and then fill the array

const data = [
     {id: 1,name: "Liam",age: 20},
     {id: 1,name: "Noah",age: 22},
     {id: 1,name: "Liam",age: 20},
     {id: 1,name: "Elijah",age: 18},
     {id: 1,name: "Elijah",age: 18}
]

const obj = data.reduce((acc, el) => { acc[el.name] = (acc[el.name] ?? 0) + 1; return acc; }, {});
const all = Object.keys(obj);
const duplicates = Object.entries(obj).filter(el => el[1] > 1).map(el => el[0]);
const uniques = Object.entries(obj).filter(el => el[1] === 1).map(el => el[0]);
console.log(all);
console.log(duplicates);
console.log(uniques);

Upvotes: 0

Reazilus
Reazilus

Reputation: 101

You need to fix your filter function.

In your version you trying to compare an array to an string.

What you need to do is something like this:

const filters = data.filter(x => resultName.includes(x.name))

Upvotes: 2

Tobias S.
Tobias S.

Reputation: 23825

Use .includes() to check if the name of an element exists inside the resultName array. You also had a typo: x.name instead of x.Name

const data = [{
    id: 1,
    name: "Liam",
    age: 20
  },
  {
    id: 1,
    name: "Noah",
    age: 22
  },
  {
    id: 1,
    name: "Liam",
    age: 20
  },
  {
    id: 1,
    name: "Elijah",
    age: 18
  },
  {
    id: 1,
    name: "Elijah",
    age: 18
  }
]
const searchName = data.map(item => item.name)
console.log(searchName);
const toFindDuplicates = arry => arry.filter((item, index) => arry.indexOf(item) !== index);
const resultName = toFindDuplicates(searchName)
console.log(resultName);
const filters = data.filter(x => resultName.includes(x.name))
console.log(filters);

Upvotes: 2

Related Questions