skip to Main Content

// this is the input. need to iterate the tech based name from object

let obj=[
        {
        name:"Nithesh",
        tech:["HTML","CSS","JAVA","JS"],
        },
        {
        name:"hari",
        tech:["NodeJS","CSS","React","JS"],
        },
        {
        name:"sathish",
        tech:["Angular","CSS","React","HTML"],
        }
    ]

//and output like this. but I tried all ways but code is not working

o/p={
    "HTML":["Nithesh","sathish"],
    "CSS":["Nithesh","hari", "sathish"],
    "JS":["Nithesh","hari"],
    "React":["hari", "sathish"],
    "NodeJs":["hari"],
    "Angular":["sathish"],
    "JAVA":["Nithesh"],
    }

3

Answers


  1. Iterate over the outer and inner arrays to find the pairs you need, and then create a new property in the result object in case you find a new language (in tech), and always append the current name to the array you have for that property:

    // Your example input:
    const arr=[{name:"Nithesh",tech:["HTML","CSS","JAVA","JS"],},{name:"hari",tech:["NodeJS","CSS","React","JS"],},{name:"sathish",tech:["Angular","CSS","React","HTML"],}];
    
    const result = {};
    for (const {name, tech} of arr) {
        for (const lang of tech) (result[lang] ??= []).push(name);
    }
    console.log(result);
    Login or Signup to reply.
  2. You can try this.

    // Define the input array of objects
    let obj = [
        {
            name: "Nithesh",
            tech: ["HTML", "CSS", "JAVA", "JS"],
        },
        {
            name: "hari",
            tech: ["NodeJS", "CSS", "React", "JS"],
        },
        {
            name: "sathish",
            tech: ["Angular", "CSS", "React", "HTML"],
        }
    ];
    
    // Initialize an empty output object
    let output = {};
    
    // Iterate over each object in the input array
    obj.forEach(person => {
        // Iterate over each technology in the current person's tech array
        person.tech.forEach(tech => {
            // Check if the technology is already a key in the output object
            if (!output[tech]) {
                // If not, create a new array for this technology
                output[tech] = [];
            }
            // Add the person's name to the array for this technology
            output[tech].push(person.name);
        });
    });
    
    // Print the output object to the console
    console.log(output);
    Login or Signup to reply.
  3. I would do it with Set, flat, reduce, filter, map and includes

     const res = [...new Set(obj.map(item => item.tech).flat())]
         .reduce((acc = {}, item, index) => {
             acc[item] = obj.filter((personData) => personData.tech.includes(item)).map((personData) => personData.name)
             return acc
      }, {})
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search