0

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

2 Answers 2

1

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

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

Comments

1

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

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.