0

I want to make parsed var array object from a local file in functionA

my law file is like below in locations.txt

-33.890542, 151.274856
-33.923036, 151.259052
-34.028249, 151.157507
-33.80010128657071, 151.28747820854187
-33.950198, 151.259302

I want to make like below parsed var array object

var locations = [
      [-33.890542, 151.274856],
      [-33.923036, 151.259052],
      [-34.028249, 151.157507],
      [-33.80010128657071, 151.28747820854187],
      [-33.950198, 151.259302]
    ];

function openTextFile() {
    var input = document.createElement("input");

    input.type = "file";
    input.accept = "text/plain";

    input.onchange = function (event) {
        processFile(event.target.files[0]);
    };

    input.click(); }   function processFile(file) {
    var reader = new FileReader();

    reader.onload = function () {
        //1) What should I do in here?
        //var parseResult = parse(reader.result); //I don't know about parse part.
    };

    reader.readAsText(file, /* optional */ "euc-kr");

     }

function initMap(parseResult) { //do something... }

I want to make like below parsed var array object via "parse function"

var locations = [
      [-33.890542, 151.274856],
      [-33.923036, 151.259052],
      [-34.028249, 151.157507],
      [-33.80010128657071, 151.28747820854187],
      [-33.950198, 151.259302]
    ];
anotherDay
  • 17
  • 3
  • Probably a bunch of `split`s: `reader.result.split("\n").map(t => t.split(","))`. If you want them to be numbers, throw a `parseFloat(n, 10)` somewhere in the mix. – zero298 Nov 05 '19 at 15:05
  • Thanks. I made it like below. reader.onload = function () { var jbString = reader.result; var jbSplit = jbString.split(','); var parseResult = []; for (var i in jbSplit ) { parseResult.push(jbSplit[i]); } }; – anotherDay Nov 05 '19 at 15:09
  • Don't use `for/in` to iterate arrays. At least use `for/of` or use the functional `map` or a good old fashioned, regular `for` loop. Please read the bottom of this answer to [Loop through an array in JavaScript](https://stackoverflow.com/a/3010848/691711) to understand why. – zero298 Nov 05 '19 at 15:12

1 Answers1

0

const text = `-33.890542, 151.274856
-33.923036, 151.259052
-34.028249, 151.157507
-33.80010128657071, 151.28747820854187
-33.950198, 151.259302`;

const output = text
  .split("\n") // Split the tuples by newline
  .map(
    t => t.split(",") // Split by comma for each pair
      .map(
        n => parseFloat(n, 10) // Make them actual numbers
      )
  );

console.log(output);
zero298
  • 25,467
  • 10
  • 75
  • 100