I want to return true if all the ids that are not null are of the same values and where flag is true. Values where flag is true and id is null are valid.
Valid list. All flags and true and all the values of the ids that are not null are of the same value ("00001")
const arr = [
{
id = '00001',
flag: true
},
{
id = "00001",
flag: true
},
{
id = "",
flag: true
}
];
Invalid: ids that are not null do not have the same value.
const arr = [
{
id = '00001',
flag: true
},
{
id = "00002",
flag: true
},
{
id = "",
flag: true
}
];
Invalid: ids are of the same value, but one flag is false.
const arr = [
{
id = '00001',
flag: true
},
{
id = "00001",
flag: false
},
{
id = "",
flag: true
}
];
Below works, but looking for a more succinct way if possible.
function meetsCriteria(arr) {
const ids = new Set();
let isValid = true;
for (const a of arr) {
if (a.id) {
ids.add(a.id);
}
if (ids.size > 1 || !a.flag) {
isValid = false;
}
if (!isValid) {
break;
}
}
return isValid;
}
Thanks.
>Solution :
You can use Array#every() and compare against the properties of the first element of the array.
const validate = (arr) =>
arr.every((a, _, [b]) => a.flag && (a.id === b.id || a.id === ''));
const arr1 = [{ id: '00001', flag: true }, { id: '00001', flag: true }, { id: '', flag: true },];
const arr2 = [{ id: '00001', flag: true, }, { id: '00002', flag: true, }, { id: '', flag: true, },];
const arr3 = [{ id: '00001', flag: true, }, { id: '00001', flag: false, }, { id: '', flag: true, },];
console.log(validate(arr1)); // true
console.log(validate(arr2)); // false
console.log(validate(arr3)); // false