Search code examples
javascriptarrayssplitconcatenation

How can I create a 2d array out of a normal array through splitting each element (in javascript)


I have got a very large string, it contains about 13000 times different data of the same kind. I have now created a function to split this string into an array of 13000 elements. Now each element of those 13000 still consists out of different data seperated with spaces (it looks something like: 20.8967489 50.29868 3 9867 86983648 How can I create a 2 dimensional array storing 5 elements for each of the 13000 elements?

I have tried something like this:

function getValuableData(){
    const fullData = [[]];
        text.replace('   ','  ');
        text.replace('  ',' ');
        const data = text.split('a')
    data.forEach(element => {
        const singleData = element.split(' ')
        fullData.concat(singleData)
    });
    }

Here is a litte section of the string: 'a1 7.0 20.172778040000026 63.561680508000052 2 2.0 a1 8.0 20.186170638000021 63.565585974000044 3 3.0 a1 9.0 20.195506026000032 63.572607051000034 4 4.0 a1 10.0 20.20404755800007 63.580019088000029 5 5.0 a1 11.0 20.212622636000049 63.587417993000031 6 6.0'


Solution

  • Let see how we can get a 2 dimensional array storing 5 elements for each using single for loop

    • update your getValuableData function
    function getValuableData(){
           text.replace('   ','  ');
           text.replace('  ',' ');
           return text.split('a');
     }
    
    
    • convert above split result to 2 dimensional array with single loop
    function get2Dimensional() {
            const oneDimArray = getValuableData();
            const rows = [];
            const itemsPerRow = 5;
    
            for (let i = 0; i < oneDimArray.length; i += itemsPerRow) {
                const row = oneDimArray.slice(i, i + itemsPerRow);
                rows.push(row);
            }
    
            return rows;
      }