There is a file whose structure looks like this:

33,40,43,45,47,49 34,40,41,45,46,48 36,40,43,45,46,48 15,39,43,44,47,49 35,40,42,45,47,49 ... 

I try to load the data of a file and write everything that is in it into a one-dimensional array, it is important that it eventually be numeric. There is one option, but it seems to me that it is inefficient because everything can be done much easier by the existing functions of JS.

My version doesn’t look like that and it doesn’t work for how much I’ve tried, it either goes undefigned or a string. For example, I did not understand how to expand the array (one-dimensional) with other arrays, so that its data would become numeric.

 if (window.File && window.FileReader && window.FileList && window.Blob) { document.getElementById('file').addEventListener('change', function(e) { var file = e.target.files[0]; var reader = new FileReader(); reader.onload = function(e) { var text = e.target.result; var newarray = text.split('\n'); for (i=0; i<newarray.length; i++) {array.concat(newarray[i].split(','));} for (i=0; i<array.length; i++) array[i] = Math.floor((array[i]/50)*100)/100; for (i=0; i<array.length-501; i++) { array2.push([array.slice(i,i+500), [array[i+501]]]); } }; reader.readAsText(file); }); } else { alert('File API is not supported!'); } 

Well, after that I make another array based on the data given. This should not affect anything, except to emphasize once again that you need to write all the data into a one-dimensional array.

    1 answer 1

    Are you trying to get an array of this type: [33, 40, 43, 45, ...] ? Then two nested loops and two calls to String.prototype.split() , just like you did. It works like this:

    1. We shove the contents of the file into a string.
    2. We run this string through String.prototype.trim() to remove the line String.prototype.trim() at the end of the file.
    3. We break this very line containing the file into multiple substrings and turn it into an array, using the newline character as a separator.
    4. We separate each substring again using a comma as a separator.
    5. We pass through each number and push into the final array.

     let file = `33,40,43,45,47,49 34,40,41,45,46,48 36,40,43,45,46,48 15,39,43,44,47,49 35,40,42,45,47,49`; file = file.trim(); let rows = file.split("\n"); let flatArray = []; for (let row in rows) { items = rows[row].split(','); for (let item in items) { flatArray.push(parseInt(items[item])); } } console.log(flatArray); 

    Instead of for...in you can also use for...of (ES6) or Array.prototype.forEach() as you like.

    • one
      Array#map would be more Array#map here. - user207618
    • @Other interesting. I heard about it before, but now I read it, a useful thing :) Thank you! - Telion