user3142695
user3142695

Reputation: 17332

JS/ES6: Check if every array element has a child in another array

There are three object arrays like this:

sections = [{ _id: '123'}]
groups   = [{ _id: '456', parent: '123' }]
items    = [{ _id: '789', parent: '456' }]

This is a valid dataset. Of course there are multiple objects in the arrays.

Now I want to check if every section has a minimum of one child group and every group have minimum one item. If this check fails, false value should be returned.

Example

sections = [{ _id: '123'}]
groups   = [{ _id: '456', parent: '123' }]
items    = [{ _id: '789', parent: 'something' }]

complete = false

In this example false should be returned, as there is no child item for the group.

I tried to start with a forEach-loop, but this is a wrong attempt:

let complete = true
sections.forEach(s => {
    if (groups.filter(g => { return g.parent === s._id }).length === 0)
        complete = false
})

Upvotes: 0

Views: 1452

Answers (2)

Jordan Bonitatis
Jordan Bonitatis

Reputation: 1547

const sections = [{ _id: '123'}];
const groups   = [{ _id: '456', parent: '123' }];
const items    = [{ _id: '789', parent: 'something' }];

const isComplete = function() {
  // check sections 
  for (const section of sections) {
    if (!groups.filter(group => group.parent == section._id).length) {
      return false;
    }
  }
  // check groups
  for (const group of groups) {
    if (!items.filter(item => item.parent == group._id).length) {
      return false;
    }
  }
  return true;
};

console.log(isComplete());

Upvotes: 0

gyre
gyre

Reputation: 16777

It looks like you have a three arrays. Two contain objects that serve as parent elements, and two contain objects that serve as child elements. You want to check whether every parent in the list of parents has a defined child.

This functionality can be achieved using a helper function everyParentHasChild(parents, children), which is built on the higher-level array methods Array#every and Array#some.

let sections = [{ _id: '123'}]
let groups   = [{ _id: '456', parent: '123' }]
let items    = [{ _id: '789', parent: '456' }]

let everyParentHasChild = (parents, children) => parents.every(
  parent => children.some(child => child.parent === parent._id)
)

let result = everyParentHasChild(sections, groups) && everyParentHasChild(groups, items)

console.log(result) //=> true

Upvotes: 3

Related Questions