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

Repeat every element in array based on object properties

I have an array that I’m retrieving from an API. The array looks like this:

[{
    "name": "Rachel",
    "count": 4,
    "fon": "46-104104",
    "id": 2
},
{
    "name": "Lindsay",
    "count": 2,
    "fon": "43-053201",
    "id": 3
},
{
    "name": "Michael",
    "count": 5,
    "fon": "46-231223",
    "id": 4
}]

Then I loop through the array to create an array containing only the names.

function buildName(data) {
  for (var i = 0; i < data.length; i++) {
    nameList.push(data[i].name)
  }
}

This also works so far, but I would like to create an array in which each name occurs as often as the object count says.

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

For example, the name Michael should appear five times in the array and Lindsay twice.

[
  "Rachel",
  "Rachel",
  "Rachel",
  "Rachel",
  "Lindsay",
  "Lindsay",
  "Michael",
  "Michael",
  "Michael",
  "Michael"
  "Michael"
]

>Solution :

I’ve upgraded your functions but you can use the map method

function buildName(data){
    for (let i = 0; i < data.length; i++){
      let numToLoop = data[i].count
      let name = data[i].name
        for (let z = 0; z < +numToLoop; z++){
          nameList.push(name)
          }
      }
 }
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