Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiple iterations of one array js

I have an array

const head = [
  {
    "id": 1,
    "name": "AK47",
    "norms": "15-18",
    "times": 2
  },
  {
    "id": 2,
    "name": "Deagle",
    "norms": "13-21",
    "times": 1
  }
]

arrays should be created from it according to the number of times properties

Something like that:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const tail = [
  {
    "id": 1,
    "headId": 1,
    "time": 1,
    "check": 16,
    "status": "ok"
  },
  {
    "id": 2,
    "headId": 1,
    "time": 2,
    "check": 14,
    "status": "less"
  },
  {
    "id": 3,
    "headId": 2,
    "time": 1,
    "check": 23,
    "status": "excess"
  }
]
  • "times": 2 was therefore 2 arrays created. Inside them is the property time meaning which time of times

How can I implement this solution more conveniently and correctly. I will be glad for any help

>Solution :

Your explanation is still a bit unclear, but from what I’ve understood, the code below might be the answer you’re looking for. It loops through the head elements and then loops x number of times, where x equals the times property. It creates an array for each element in head and then flattens it to generate the desired 1D array output.

const head = [{
    "id": 1,
    "name": "AK47",
    "norms": "15-18",
    "times": 2
  },
  {
    "id": 2,
    "name": "Deagle",
    "norms": "13-21",
    "times": 1
  }
];

let idIdx = 1;
const res = head.flatMap((obj) => {
  let arr = [];
  for (let i = 0; i < obj.times; i++)
    arr.push({
      id: idIdx++,
      headId: obj.id,
      time: i + 1
    });
  return arr;
});

console.log(res);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading