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

every() es6 for nested array is not working?

I expect true for below usage of every but it wasn’t, what’s wrong with my logic?


const isAllChecked = [
    {
        "id": "1",
        "checked": true,
    },
    {
        "id": "2",
        "checked": true,
        "nested": [
            {
                "id": "2.1",
                "checked": true,
            },
            {
                "id": "2.2",
                "checked": true,
            }
        ]
    },
    {
        "id": "3",
        "checked": true,
    },
].every(
    (o) =>
      o.checked &&
      o.nested?.every((o) => o.checked)
  )

What I wanted: if any of the level 1 checked or nested checked is false then isAllChecked is false, but if non of the checked property in level 1 or nested is false, isAllChecked should return true.

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

>Solution :

Optional chaining will evaluate to undefined if the chain fails, so for the second iteration

(o) =>
  o.checked &&
  o.nested?.every((o) => o.checked)

will evaluate to

(o) =>
  true
  undefined

You probably wanted

(o) =>
  o.checked &&
  (!o.nested || o.nested.every((o) => o.checked))

or

(o) =>
  o.checked &&
  (o.nested || []).every(o => o.checked)
const isAllChecked = [
    {
        "id": "1",
        "checked": true,
    },
    {
        "id": "2",
        "checked": true,
        "nested": [
            {
                "id": "2.1",
                "checked": true,
            },
            {
                "id": "2.2",
                "checked": true,
            }
        ]
    },
    {
        "id": "3",
        "checked": true,
    },
].every(
    (o) =>
      o.checked &&
      (o.nested || []).every((o) => o.checked)
  )
console.log(isAllChecked);
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