skip to Main Content

I have array of object arrobj and arrlist prgList,

I need to fetch the name from the arrobj based on the programs in the list using javascript.

If the program prg exists in the arrobj , fetch and should display as show in expectd output

tried

var lists=[]
var result =arrobj.find(e=> e.prg.includes(prgList) ? lists.push(e))); // bit stuck

var arrobj=[
  {id:1, name: "user1", prg: ["onex", "twox", "threex"]},
  {id:2, name: "user2", prg: ["onex", "threex"]},
  {id:3, name: "user3", prg: ["twox", "threex"]}
]

var prgList =["onex", "twox", "threex"]

Expected Output:

{
  onex: ["user1", "user2"],
  twox: ["user1", "user3"],
  threex: ["user1", "user2", "user3"]
}

2

Answers


  1. You can do something like this:

    var arrobj=[
      {id:1, name: "user1", prg: ["onex", "twox", "threex"]},
      {id:2, name: "user2", prg: ["onex", "threex"]},
      {id:3, name: "user3", prg: ["twox", "threex"]}
    ];
    
    var prgList =["onex", "twox", "threex"];
    
    var result = prgList.reduce((a, key) => {
      const users = arrobj.reduce((acc, curr) => (curr.prg.includes(key) ? [...acc, curr.name] : acc), []);
      return { ...a, [key]: users };
    }, {});
    
    console.log(result);
    Login or Signup to reply.
  2. You can do for instance as following:

    const input =[
      {id:1, name: "user1", prg: ["onex", "twox", "threex"]},
      {id:2, name: "user2", prg: ["onex", "threex"]},
      {id:3, name: "user3", prg: ["twox", "threex"]}
    ]
    
    const prgList =["onex", "twox", "threex"]
    
    const output = Object.fromEntries(prgList.map(key => [
        key, 
        input.filter(x => x.prg.includes(key)).map(x => x.name)
        ]))
     
     console.log(output);

    From each element in prgList create a [key, value] pair, where the element is the key and the value is the list of users, which contain the key, mapped to their names only.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search