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

Convery array of strings to array of objects – every 3rd index

I’m trying to convert an array of strings to an array of objects after every 3rd index.

Input:

let tee = [
  'Blue',             '130',
  '70.8',             'Blue',
  '128',              '708',
  'White',            '124',
  '68.2'
]

Code:

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

            function fillTeeBoxes(holesAmount) {
            for (let i = 0; i < holesAmount.length; i++) {
                let teeBox = ['tee', 'slope', 'rating']
                let holeData = {};
                for (let j = 0; j < 3; j++) {
                    holeData[teeBox[j]] = parseInt(getTeeBoxes[i]) || getTeeBoxes[i]
                    i++
                };
                teeBoxes.push(holeData)
            };
        };

Expected Output:

    tee = [
      {tee: 'Blue', slope: 130, handicap: 70.8}
      {tee: 'Blue', slope: 128, handicap: 70.8}
      {tee: 'White', slope: 124, handicap: 68.2}
    ]

>Solution :

We can use a for loop and iterate in steps of 3:

let tee = [
  'Blue',             '130',
  '70.8',             'Blue',
  '128',              '708',
  'White',            '124',
  '68.2'
];
var output = [];

for (var i=0; i < tee.length; i+=3) {
    var obj = {tee:tee[i], slope:tee[i+1], handicap:tee[i+2]};
    output.push(obj);
}

console.log(output);
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