Home > Enterprise >  Print element of an object in sequence
Print element of an object in sequence

Time:11-12

Print elements from object. Ex.

const emps = {
    "Jacobs": ["Emiel", "Svjetlana", "Ivanna"],
    "Ivanna": ["Michael", "Lawson"],
    "Emiel": ["John", "Ruby"],    
    "Lawson": [],
    "Michael": ["Lindsay", "Ferguson"],
    "Ferguson": []
}

In above example lets suppose "Jacob" is Parent of "Emiel", "Svjetlana", "Ivanna", so we have to print sequence "Jacob" "Emiel", "Svjetlana", "Ivanna" means first Parent then childs.

Output should be: 
"Jacob" 
"Emiel"
"Svjetlana"
"Ivanna"
"Emiel"
"John"
"Ruby"
"Ivanna"
"Michael"
"Lawson"
"Michael"
"Lindsay"
"Ferguson"

CodePudding user response:

const emps = {
  "Jacobs": ["Emiel", "Svjetlana", "Ivanna"],
  "Ivanna": ["Michael", "Lawson"],
  "Emiel": ["John", "Ruby"],
  "Lawson": [],
  "Michael": ["Lindsay", "Ferguson"],
  "Ferguson": []
}

const empsArr = Object.entries(emps)
const empsParents = Object.keys(emps)
const firstChildren = empsArr.map(arr =>
  arr[1][0]
)
let leftParents = empsParents.filter(item => item !== empsParents[0]);

const result = empsArr.reduce((acc) => {
  const firstChild = acc.firstChild;
  // if has children add it and its children
  if (emps[firstChild] ?.length > 0) {
    leftParents = leftParents.filter(item => item !== firstChild);
    return {
      res: [...acc.res, firstChild, ...emps[firstChild]],
      firstChild: emps[firstChild][0]
    }
  } else {
    // if has no children move on to the item which has not already been added and is not the first child of any item
    const newParent = leftParents.find(pName => !firstChildren.includes(pName))
    leftParents = leftParents.filter(item => item !== newParent)
    if (emps[newParent]) {
      const newParentData = emps[newParent].length > 0 ? [newParent, ...emps[newParent]] : []
      const firstChildData = typeof emps[firstChild] !== "undefined" ? [firstChild] : []
      const newFirstChild = emps[newParent][0];
      return {
        res: [...acc.res, ...newParentData, ...firstChildData],
        firstChild: newFirstChild
      }
    } else
      return acc
  }
}, {
  res: [
    empsParents[0], ...emps[empsParents[0]]
  ],
  firstChild: emps[empsParents[0]][0]
})
result.res.map(item=>console.log(`"${item}"`))

CodePudding user response:

You can use the following code:

const emps = {
    "Jacobs": ["Emiel", "Svjetlana", "Ivanna"],
    "Ivanna": ["Michael", "Lawson"],
    "Emiel": ["John", "Ruby"],    
    "Lawson": [],
    "Michael": ["Lindsay", "Ferguson"],
    "Ferguson": []
}

function print(obj) {
    for(let x in obj) {
        console.log(x);
        obj[x].forEach(val => console.log(val));
    }
}

print(emps);

  • Related