skip to Main Content

In the below examples, why am I not getting any value?

const people = [{
    name: "mike",
    jobs: ["waiter", "doctor"]
  },
  {
    name: "nils",
    jobs: ["singer", "actor"]
  },
  {
    name: "nils",
    jobs: ["nurse", "actor"]
  },
]


const iterate = people.map(person => {
  return person.jobs.map(job => {
    return job;
  })
  return res;
})
console.log(iterate)
const people = [{
    name: "mike",
    jobs: ["waiter", "doctor"]
  },
  {
    name: "nils",
    jobs: ["singer", "actor"]
  },
  {
    name: "nils",
    jobs: ["nurse", "actor"]
  },
]

let res = []
const iterate = people.map(person => {
  return person.jobs.map(job => {
    res.push(job)
  })
  return res;
})
console.log(iterate)

4

Answers


  1. The code reformats the data from an array of objects into a new array of arrays. Each inner array now contains the jobs of a specific person.

    const people = [
      {
        name: "mike",
        jobs: ["waiter", "doctor"]
      },
      {
        name: "nils",
        jobs: ["singer", "actor"]
      },
      {
        name: "nils",
        jobs: ["nurse", "actor"]
      }
    ];
    
    const iterate = [].concat(...people.map(person => person.jobs));
    console.log(iterate);
    Login or Signup to reply.
  2. Another approach using .flat(Infinity) method:

    const people = [
      {
        name: "mike",
        jobs: ["waiter", "doctor"]
      },
      {
        name: "nils",
        jobs: ["singer", "actor"]
      },
      {
        name: "nils",
        jobs: ["nurse", "actor"]
      }
    ];
    
    const iterate = people.map(person => person.jobs).flat(Infinity)
    console.log(iterate);
    Login or Signup to reply.
    • I don’t know much fancy way of writing this, but here is my solution.
    • You want to extracts jobs from people array of object.
    • What I did below is just created one variable to store job values.
    • Loop thour array of object and looped though jobs key value of each person and pushed it inside that array we have created.
    const people = [{
        name: "mike",
        jobs: ["waiter", "doctor"]
      },
      {
        name: "nils",
        jobs: ["singer", "actor"]
      },
      {
        name: "nils",
        jobs: ["nurse", "actor"]
      },
    ]
    
    const jobs = [];
    const iterate = people.forEach(person => {
      person.jobs.forEach(job => {
        jobs.push(job);
      })
    })
    console.log(jobs)
    Login or Signup to reply.
  3. Thanks to @pilchard for the suggestion flatMap:

    const people = [
      {
        name: "mike",
        jobs: ["waiter", "doctor"]
      },
      {
        name: "nils",
        jobs: ["singer", "actor"]
      },
      {
        name: "nils",
        jobs: ["nurse", "actor"]
      }
    ];
    const iterate = people.flatMap(person => person.jobs)
    console.log(iterate);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search