Home > Net >  Find duplicates and check for duplicate elements inside the object in JavaScript
Find duplicates and check for duplicate elements inside the object in JavaScript

Time:10-12

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

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

The description of your issue is not entirely clear to me, but it sounds like you want to group the items based on name. Then do some checks based on the resulting groups.

const data = [
  { id: 1, name: "Liam",   age: 18 },
  { 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 peopleByName = groupBy(data, person => person.name);
for (const [name, people] of peopleByName) {
  const isDuplicate = people.length > 1;
  const haveSameAge = people.every(person => person.age == people[0].age);
  
  if (isDuplicate && haveSameAge) {
    console.log(name, "is a duplicate");
  } else if (isDuplicate) {
    console.error(name, "duplicate with different ages");
  } else {
    console.log(name, "is unique");
  }
}

// helper
function groupBy(iterable, fnKey) {
  const groups = new Map();
  for (const item of iterable) {
    const key = fnKey(item);
    if (!groups.has(key)) groups.set(key, []);
    groups.get(key).push(item);
  }
  return groups;
}

CodePudding user response:

Here's a check for duplicate records (name and age) in the array, using a reducer function on the entries the data. For methods used, study

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

const duplicateCheck = data => Object.fromEntries(
  Object.entries( data.reduce( (acc, r) => {
    const okRec =  acc[`${r.name}${r.age}`]
      ? { [`id${r.id}`]: `Name: ${r.name}, age: ${r.age} => more then once` }
      : { [`${r.name}${r.age}`]: `ok` };
    return {... acc, ...okRec };
  }, {} ) )
  .filter( ([key, value]) => value.endsWith(`more then once`) )
);

console.log(duplicateCheck(data));

// to only determine if the data array contains duplicates according
// to your criteria (name, age) use:
console.log(`[data] has duplicates? ${
  Object.keys(duplicateCheck(data)).length > 0}`);

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

// generic function to check for duplicates with certain keys
// in an array of objects
function hasDuplicatesForKeys(data, ...keys) {
  let check = new Set();
  data.forEach( d => check.add( keys.map( k => d[k] ).join(``) ) );
  return [...check].length < data.length;
}

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') }`);
  
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: 4, name: "Liam", age: 20},
     {id: 4, name: "Liam", age: 18},
     {id: 4, name: "Noah", age: 20},
     {id: 4, name: "Noah", age: 18},
     {id: 4, name: "Elijah", age: 18} ],
  ];   
}

  • Related