TransWikia.com

Javascript map inside of map till condition satisfied

Stack Overflow Asked by Ohsik on November 15, 2021

I like to pass id then get number of all descendant items. e.g. if pass 10 it will return 2 because there’s 2 items { id: 7, report: 10 } and { id: 4, report: 7 }.

let Data = [
  { id: 10, report: -1 },
  { id: 7, report: 10 },
  { id: 3, report: -1 },
  { id: 4, report: 7 }
];

This code only works for the Data above but won’t work if there’s more data added such as { id: 5, report: 4 }. How do I make this work?

function countItems(id){
  let count = 0;

  Data.map( em => {
    if(em.report === 10) {
      count++
      
      orgChart.map( ema => {
        if(ema.report === em.id) {
          count++
        }
      })
      
    }
  })

  return count;
}

2 Answers

A more declarative approach:

const countItems = (id, data) => {
  const datum = data.find(({ report }) => report == id);
  return datum ? 1 + countItems(datum.id, data) : 0;
}

Answered by GirkovArpa on November 15, 2021

Treat each each object finding as a separate task. If one object is found then check if the next object is available or not untill no object is available with that id.

// Using recursion
function countItems(id, data){
    for (const item of data){
        if(item.report == id){
            return 1 + countItems(item.id, data);
        }
    }
    return 0;
}


let data = [
  { id: 10, report: -1 },
  { id: 7, report: 10 },
  { id: 3, report: -1 },
  { id: 4, report: 7 }
];
   
console.log(countItems(10, data)); // it will print 2
console.log(countItems(-1, data)); // it will print 3

// Using Loop
function countItemsUsingLoop(id, data){
    count  = 0;
    found = false;
    do{
        found = false;
        for (const item of data){
          if(item.report == id){
          found = true;
          id = item.id;
          count++;
          break;
          }
        }
    }while(found);
    return count;
}

console.log(countItemsUsingLoop(10, data)); // it will print 2
console.log(countItemsUsingLoop(-1, data)); // it will print 3

Answered by Kaushal Kumar on November 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP