convert array to array of array - javascript

I am getting data from a Firebase database and want to be able to pass it into a function to be used in a Google Map. The required/desired format is below. I can get the data from Firebase into an but want to reformat it somehow to put it into the correct format.
I have passed the array itself and then tried to push it into the locations array but that obviously doesn't work.
Here is a console.log(); of the array and the format.
Current Array:
var array = ["Stop1, 37.3329891813207, -122.039420719004", "Stop2, 37.3320091546085, -122.036849794357", "Stop3, 37.3310547072562, -122.034668026436", "Stop4, 37.3301791417375, -122.033242200136", "Stop5, 37.3307185698498, -122.030606204886"]
initMap(array)
Desired Format:
function initMap(passedArray) {
//..Convert array here?..
var locations = [
['Stop1', 37.3329891813207, -122.039420719004],
['Stop2', 37.3320091546085, -122.036849794357],
['Stop3', 37.3310547072562, -122.034668026436],
['Stop4', 37.3301791417375, -122.033242200136],
['Stop5', 37.3307185698498, -122.030606204886]
];
}
Thanks.

Split by separator ', ' and parse numbers.
var array = ["Stop1, 37.3329891813207, -122.039420719004", "Stop2, 37.3320091546085, -122.036849794357", "Stop3, 37.3310547072562, -122.034668026436", "Stop4, 37.3301791417375, -122.033242200136", "Stop5, 37.3307185698498, -122.030606204886"]
const initMap = array => array
.map(str => str.split(', ').map((x, i) => (i ? parseFloat(x) : x)))
console.log(initMap(array))

Related

Extracting and converting data from JSON via js

Good evening! There is a script that converts data into an array, I would like to know how it can be upgraded so that you can convert and extract data for each object (arb, astar, aurora, avax, baba, bsc, etc.), the data in the screenshot.
The script for converting data into an array (currently extracts only from bsc):
var data = {(Screenshot)};
var output = Object.keys(data.bsc.token_dict).map(k => data.bsc.token_dict[k]);
console.log(output);
Give this a try:
const output = Object.entries(data)
.map((k, v) => ({chain: k, token_dict: Object.values(v.token_dict)}));

Retrive alle values as array on key in firebase for react native

Hey i have a list of calendar evnets where the key is by date but i would like u get out all values as a array of data
but i wish to get the data out kinda like this but ofc with the rest of the values i have
'2012-05-25': [{date: '2021-04-10', name: "",},{date: '2021-04-10', name: "",}]
is there any way using firebase query to get it out in the format over ?
Something like this should do the trick:
cons ref = firebase.database.ref("calendar/events");
ref.once("value").then((snapshot) => {
let result = {};
snapshot.forEach((daySnapshot) => {
result[daySnapshot.key] = [];
daySnapshot.forEach((eventSnapshot) => {
result[daySnapshot.key].push(eventSnapshot.val());
})
})
console.log(result);
});
So we load all data from the database and then use two nested forEach loops to handle the dynamic levels underneath, and result[daySnapshot.key] to get the date key.

How to store data retrieved from the server into an array with JavaScript?

Can someone tell me how can I store the values of the CSV file into an array that I am retrieving from the web server.
Data example:
Time2,Price,Size
0.0,20998.0,69
0.0,20999.0,18042
0.0,21001.0,14783
0.0,21003.0,100
Suppose I have the following scenario shown below:
var url1 = 'path for CSV file'
$.get(url1, function(data) {
// data param contains all the data that I retrieved from the csv
});
using the above example, how can I store my data into an array so the end result looks like the following:
A very straight forward approach:
Split into lines on \n
Split each line ,
const csv = `Time2,Price,Size
0.0,20998.0,69
0.0,20999.0,18042
0.0,21001.0,14783
0.0,21003.0,100`;
const result = csv.split("\n").map(l=>l.split(','));
console.log(result);
Use a reducer (Array.reduce):
// create an array of arrays
const csvLines = `Time2,Price,Size
0.0,20998.0,69
0.0,20999.0,18042
0.0,21001.0,14783
0.0,21003.0,100`
.split("\n")
.map(v => v.split(","));
// bonus: to array of objects
let headers = csvLines.shift();
const fromCsv = csvLines.reduce( (acc, val) => [...acc, {
[headers[0]]: parseFloat(val[0]),
[headers[1]]: parseFloat(val[1]),
[headers[2]]: parseFloat(val[2]) } ], []);
console.log(fromCsv);

D3.js array double quotes after .map

I have the following code:
d3.csv("static/data/river.csv", function(data) {
var latlongs = data.map(function(d) { return [d.Lat,d.Lng]; })
var lineArray1 = latlongs;
console.log(lineArray1);
I get an output lineArray1 that looks like [Array(2), Array(2), Array(2)....] and so on. But when I take a look at the actual Array(2)'s they look like:
["-35.48642101", "144.8891555"]
["-35.48695061", "144.8893026"]
["-35.48704283", "144.889315"]
Is there a way to get rid of the double quotes at the start? I tried lineArray1.map(Number) but this just generated an array of NaNs for some reason. The output I want is:
[-35.48642101, 144.8891555]
[-35.48695061, 144.8893026]
[-35.48704283, 144.889315]
Thanks!
It looks like d.Lat and d.Lng are strings, so if you want to convert them to numbers, call Number on them:
var latlongs = data.map(function(d) { return [Number(d.Lat), Number(d.Lng)]; });
Or, to not repeat Number twice, use .map again inside:
var latlongs = data.map(function(d) { return [d.Lat, d.Lng].map(Number); });
Or, in modern JS:
const latlongs = data.map(({ Lat, Lng }) => [Lat, Lng].map(Number));
Your lineArray1.map(Number) didn't work because lineArray1 contains arrays (of numbers), and not numbers alone, and calling Number on an array doesn't work.

JSON to JS array

JSON:
[{"CDATE":"0000-00-00","DISTANCE":"0"},
{"CDATE":"0000-00-00","DISTANCE":"1"},
{"CDATE":"0000-00-00","DISTANCE":"2"},
{"CDATE":"0000-00-00","DISTANCE":"3"}]
Is it possible to put all the distance value in their own array in JS? The formatting will be consistent as it comes from an API and is always formatted correctly.
What I've tried:
var arry = [ /* JSON noted above */ ];
alert(arry[1])
and
var arry = JSON.parse([ /* JSON noted above */ ]);
alert(arry[1])
Expected:
1
Actual:
{"CDATE":"0000-00-00","DISTANCE":"1"}
and the other gives an error.
I would like to extract just the DISTANCE value as an array of DISTANCE
I've tried JSON.parse() but I don't think this is what I am after as it hasn't worked for me.
Use .map
var data = [{"CDATE":"0000-00-00","DISTANCE":"0"},
{"CDATE":"0000-00-00","DISTANCE":"1"},
{"CDATE":"0000-00-00","DISTANCE":"2"},
{"CDATE":"0000-00-00","DISTANCE":"3"}];
var distance = data.map(el => el.DISTANCE);
console.log(distance[2]);
console.log(distance);
It is already a valid json so you do not need to use JSON.parse()

Categories

Resources