Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

78
Views
Find duplicates and check for duplicate elements inside the object in JavaScript

I have an array that contains some objects I want to find duplicate names in the array After finding the duplicate names of each duplicate name, I should also check their age. In addition to having the same name, if the age is not the same but the names are the same, save it and give me an error only if the name is the same and the same age. My array has duplicate names that are not the same age Now the program I wrote gives an error and should not give an error because the names are the same but their age is not the same and should be saved and not done correctly After searching the array, I found duplicate name. Two duplicate Liam names are equal in age. Give an error in the console, but if the age is not equal, do not make a mistake and it will be Thank you for helping me answer

const data = [
     {id: 1,name: "Liam",age: 20},
     {id: 2,name: "Liam",age: 18},
     {id: 3,name: "Noah",age: 20},
     {id: 4,name: "Noah",age: 18},
     {id: 5,name: "Elijah",age: 18}
]

    function checked() {
        const toFindDuplicates = arry => arry.filter((item, index) => arry.indexOf(item) !== index);
        const getName = data.map(item => item.name)
        const duplicateName = toFindDuplicates(getName)
        console.log(duplicateName);
        if (duplicateName.length > 0) {
            const newArray = []
            const filters = data.filter(x => duplicateName.includes(x.name))
            filters.forEach(item => newArray.push(item.age))
            console.log(filters);
            const duplicateAge = toFindDuplicates(newArray)
            if (!!duplicateName.length) {
                console.log("error");
            } else {
                return console.log("save");;
            }
        } else {
            return console.log("save");;
        }
    }
    checked()

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

If I understood your question correctly, you simply want to detect if your data has the same name age pair. You can check it like this:

const data1 = [
     {id: 1,name: "Liam",age: 20},
     {id: 2,name: "Liam",age: 18},
     {id: 3,name: "Noah",age: 20},
     {id: 4,name: "Noah",age: 18},
     {id: 5,name: "Elijah",age: 18}
]

const data2 = [
     {id: 1,name: "Liam",age: 20},
     {id: 2,name: "Liam",age: 18},
     {id: 3,name: "Noah",age: 20},
     {id: 4,name: "Noah",age: 18},
     {id: 5,name: "Elijah",age: 18},
     {id: 6,name: "Liam",age: 18},
]

const duplicateExists = arr => {
  let error = false, obj = {}
  arr.forEach(el => {
    if(!error){
      const {name,age} = el
      if(obj[name]) {
        error = obj[name] === age
      }
      obj[name] = age
    }
  } ,{})
  return error
}

console.log(duplicateExists(data1))
console.log(duplicateExists(data2))

about 4 years ago · Juan Pablo Isaza Report

0

For an O(N) single-pass solution you could consider utilizing a Map that uses the name as a key and a Set of previously seen ages corresponding to the name as the value, since lookup into a Set is O(1):

const data = [
    {id: 1, name: "Liam", age: 20},
    {id: 2, name: "Liam", age: 18},
    {id: 3, name: "Noah", age: 20},
    {id: 4, name: "Noah", age: 18},
    {id: 5, name: "Elijah", age: 18},
];

const hasDuplicates = arr => {
    const nameToAges = new Map();
    for (const {_, name, age} of arr) {
        if (nameToAges.has(name)) {
            if (nameToAges.get(name).has(age)) {
                return true;
            }
            nameToAges.get(name).add(age);
        } else {
            nameToAges.set(name, new Set([age]));
        }
    }
    return false;
}

console.log("Two elements exist with same name and age:");
console.log(hasDuplicates(data));

Try it out here.

about 4 years ago · Juan Pablo Isaza Report

0

[Edit: Removed the complex solution]

If you just want to check for any duplicate in the array, using a Set simplifies things a lot. Here's a more generic function to check for duplicates on any (combination of) key(s) in an array of Objects.

const [data, data2] = getExampleData();
console.log(`hasDuplicatesForKeys(data, 'name', 'age'): ${ 
  hasDuplicatesForKeys(data, 'name', 'age') }`);
console.log(`hasDuplicatesForKeys(data2, 'name', 'age'): ${ 
  hasDuplicatesForKeys(data2, 'name', 'age') }`);
// name and id
console.log(`hasDuplicatesForKeys(data2, 'name', 'id'): ${
  hasDuplicatesForKeys(data2, 'name', 'id') }`);
// single key
console.log(`hasDuplicatesForKeys(data2, 'name'): ${
  hasDuplicatesForKeys(data2, 'name') }`);
console.log(`hasDuplicatesForKeys(data, 'id'): ${
  hasDuplicatesForKeys(data, 'id') }`);

/**
 * Generic function to check for duplicate Object 
 * on certain keys within an array of objects
 * @param data {Array} The array
 * @param keys {string[]} The keys to filter on 
 * @returns {boolean}
 */
function hasDuplicatesForKeys(data, ...keys) {
  let check = new Set();
  data.forEach( d => check.add( keys.map( k => d[k] ).join(``) ) );
  return [...check].length < data.length;
}

// keep data out of sight
function getExampleData() {
  return [
    [
     {id: 1, name: "Liam", age: 20},
     {id: 2, name: "Liam", age: 18},
     {id: 3, name: "Noah", age: 20},
     {id: 3, name: "Noah", age: 20},
     {id: 4, name: "Noah", age: 18},
     {id: 5, name: "Elijah", age: 18},
     {id: 12, name: "Elijah", age: 18} ],
   [
     {id: 1, name: "Liam", age: 20},
     {id: 2, name: "Liam", age: 18},
     {id: 3, name: "Noah", age: 20},
     {id: 4, name: "Noah", age: 18},
     {id: 5, name: "Elijah", age: 18} ],
  ];   
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!