Home > Mobile >  check if duplicates exist in array object
check if duplicates exist in array object

Time:12-13

I want to reaturn true/false if there is some duplicates on object array.

arr = [
     { nr:10, name: 'aba' },
     { nr:11, name: 'cba' },
     { nr:10, name: 'aba' }
]

 arr2 = [
         { year:2020, city: 'Aaa' },
         { year:2010, city: 'Bbb' },
         { year:2020, city: 'Aaa' }
    ]

I found many solutions for one value but what if we want to check the whole object. Do I have to do foreach?

 const result: T[] = [];
    for (const item of array) {
        if (!result.includes(item)) {
            result.push(item);
        }
    }
    return result;

CodePudding user response:

you can use JSON.stringify and map and some array methods.

let arr = [
     { nr:10, name: 'aba' },
     { nr:11, name: 'cba' },
     { nr:10, name: 'aba' }

]


 let valuesStringify = arr2.map(x => JSON.stringify(x));

 let duplicate = valuesStringify.some((item, i) => valuesStringify.indexOf(item) !== i)

console.log(duplicate) //true

enter link description here

CodePudding user response:

Using combo of Array.prototype.some, Array.prototype.every and Object.entries

This checks each item of array against the rest of the array (slice(index 1)) to see if some object is equal.

function hasDuplicates(arr) {
  // check each item of array against rest of the array
  return arr.some((obj, index) => arr.slice(index   1).some(obj2 => {
    // check obj is equal obj2
    return Object.entries(obj).every(([key, value]) => obj2[key] === value)
  }))
}

let arr = [
  { nr:10, name: 'aba' },
  { nr:11, name: 'cba' },
  { nr:10, name: 'aba' }
];

let arr2 = [
  { year:2020, city: 'Aaa' },
  { year:2010, city: 'Bbb' },
  { year:2020, city: 'Ccc' }
];

console.log(hasDuplicates(arr)); // true
console.log(hasDuplicates(arr2)); // false

  • Related