Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Verify only single value of one property in an array and matches criteria

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading