'check array of objects if specific value is unique across all the array

I have an array like this

const arr = [{ name: 'sara' }, { name: 'joe' }];

and i want to check if name is unique across the array so

const arr = [{ name: 'sara' }, { name: 'joe' }];//sara is unique //true
const arr = [{ name: 'sara' }, { name: 'sara' },{ name: 'joe' }];//sara is unique //false

i know there's array.some but it doesn't help in my situation

whats is the best way to achieve that using javascript thanks in advance



Solution 1:[1]

You could take a single loop and a Set for seen value.

isUnique is a function which takes a property name and returns a function for Array#every.

const
    isUnique = (key, s = new Set) => o => !s.has(o[key]) && s.add(o[key]),
    a = [{ name: 'sara' }, { name: 'joe' }],
    b = [{ name: 'sara' }, { name: 'sara' }, { name: 'joe' }];

console.log(a.every(isUnique('name'))); //  true
console.log(b.every(isUnique('name'))); // false

Solution 2:[2]

i have this implementation and it dose the job

const arr = [{ name: "salah" }, { name: "joe" }];

let bols = [];
arr.forEach((item1, i1) => {
  arr.forEach((item2, i2) => {
    if (i1 !== i2) {
      bols.push(item2.name === item1.name);
    }
  });
});

bols.some((item) => item === true);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 SalahEddineBeriani