1

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);

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

Comments

2

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))

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.