1

I have a CSV file whith this kind of lines:

1,New York city,8175133,40.71455,-74.007124

2,Los Angeles city,3792621,34.05349,-118.245323

I'm doing this method to split it:

function processData(csv) {
    var allTextLines = csv.split(/\r\n|\n/);
    var lines = [];
    while (allTextLines.length) {
        lines.push(allTextLines.shift().split(','));
    }
    console.log(lines);
    drawOutput(lines);
}

But it doesn't work like the way I want. I would like just a part of the string and not teh whole line:

lines[0] = New York City, 40.71455, -74.007124

lines[1] = Los Angeles city, 34.05349, -118.245323

Is it possible? How Can I split it that way? Already tried a few things, but I didn't find yet a good way to do it.

0

1 Answer 1

2

The easiest solution would be something like this:

while (allTextLines.length) {
    var line = allTextLines.shift().split(',');
    lines.push([line[1], line[3], line[4]]);
}

Since you only want the 2nd, 4th and 5th elements from the original data.

However, you could make it a little easier to access like this:

lines.push({city: line[1], lat: line[3], lon: line[4]});

This will result in something like:

lines[0] === {city: "New York City", lat: 40.71455, lon: -74.007124}
lines[1] === {city: "Los Angeles city", lat: 34.05349, lon: -118.245323}

Meaning you can just use: lines[0].city.

Or, if you want just those 3 "elements" as a string:

lines.push(line[1] + ', ' + line[3] + ', ' + line[4]);

Resulting in:

lines[0] === "New York City, 40.71455, -74.007124";
lines[1] === "Los Angeles city, 34.05349, -118.245323";
Sign up to request clarification or add additional context in comments.

2 Comments

@heisenberg: Excellent, thanks! Did you indeed need the first suggestion I gave, or one of the other 2?
first one is more then enough because I will never show the data, I will just use it to point the locations in google maps

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.