Combining Two Arrays To One in NodeJS - arrays

I want to create Excel file that consist of 2 arrays of data with ExcelJS.
I can create the Excel file:
var Excel = require('exceljs');
var workbook = new Excel.Workbook();
var sheet = workbook.addWorksheet('My Sheet', {properties:{tabColor:{argb:'FFC0000'}}});
I can add column headers:
sheet.columns = [{key:"date", header:"Date"}, {key: "quantity", header: "Quantity"}]
I got 2 arrays for these columns:
array_date = [2018-01-04, 2018-01-06, 2018-01-08, 2018-01-09]
array_quantity = [25, 32, 54, 48]
I want to combine these 2 arrays to one array like this:
var merged = [{date:"2018-01-04", quantity:25}
, {date:"2018-01-06", quantity:32}
, {date:"2018-01-08", quantity:42}
, {date:"2018-01-09", quantity:48}];
If I can combine, I able to add as row for every data:
for(i in merged){
sheet.addRow(merged[i]);
}
Then I can create the Excel File:
workbook.xlsx.writeFile("some.xlsx").then(function() {
console.log("xls file is written.");
});
How can I combine two arrays to one If they are ordered? Also, I'm wondering is this the best approach to create excel file in NodeJS?

You can create the new array with
var array_date = ["2018-01-04", "2018-01-06", "2018-01-08", "2018-01-09"];
var array_quantity = [25, 32, 54, 48];
var merged = array_date.map((date, i) => ({
date,
quantity: array_quantity[i],
}));

array_date = [2018-01-04, 2018-01-06, 2018-01-08, 2018-01-09]
array_quantity = [25, 32, 54, 48]
var merged=[];
for(var i=0;i<array_date.length;i++){
merged.push({date:array_date[i], quantity:array_quantity[i]});
}
console.log(merged);

Related

Create an array while iterating Angular

I am getting the IDs from an array when I select a few rows (a lot of data is coming in and I only need the IDs). I want that when obtaining the IDs an array is created for me ONLY with the IDs. The problem is that when I try I get the following (by console):
Id Seleccionado: 78
Id Seleccionado: 79
Id Seleccionado: 81
And I would like to obtain them as a normal array:
{ 78, 79, 81 }
TS
procesarClic() {
const request = this.selection.selected;
for (let i = 0; i < request.length; i++){
const list = request[i].id;
console.log('Id Seleccionado: ', list);
}
}
The request constant it is where the selected rows are with all the data in the array, since many rows can be selected.
Thank you for your contribution and help!
You have to create the array and filling it up like this:
procesarClic() {
const request = this.selection.selected;
let array = [];
for (let i = 0; i < request.length; i++){
const list = request[i].id;
console.log('Id Seleccionado: ', list);
array.push(request[i].id);
}
}
This way, you will have an array with only ids in it.
BR
Assuming this.selection.selected is an array which it seems to be, you could use the map function, ie.
const examples = [
{id: 1, name: "One"},
{id: 2, name: "Two"},
{id: 3, name: "Three"}
]
const onlyIds = examples.map(e => e.id);
console.log(onlyIds);
which would return an array consisting of ids only.

Leaflet: iterate through data for custom markers

I need your help with custom markers in Leaflet. I need custom markers that correspond with the data entries. Here is a data SAMPLE csv that looks like this:
result
display_na
lat
long
AV
14, Amsterdamer Straße, Leopoldkiez, Wedding, Mitte, Berlin, 13347, Deutschland
13.3574034
52.5517197
VK
Seestraße, Wedding, Mitte, Berlin, 13351, Deutschland
52.541301
13.3341968
This is my code by now
// create 3 types of markers in 3 colors
var LeafIcon = L.Icon.extend({
options: {
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
},
});
// Read markers data from data.csv
$.get("./data.csv", function (csvString) {
// Use PapaParse to convert string to array of objects
var data = Papa.parse(csvString, { header: true, dynamicTyping: true }).data;
var greenIcon = new LeafIcon({ iconUrl: "greeb.png" }),
yellowIcon = new LeafIcon({ iconUrl: "yellow.png" }),
redIcon = new LeafIcon({ iconUrl: "red.png" });
// For each row in data, create a marker and add it to the map
// For each row, columns `Latitude`, `Longitude`, and `Title` are required
for (var i in data) {
var row = data[i];
var marker = L.marker([row.lat, row.long], {
opacity: 1,
}).bindPopup(row.display_na);
L.marker([row.lat, row.long])
.addTo(map)
.bindPopup(row.display_na)
.openPopup();
}
});
It's not working. Can you tell me where my failure lies? I have 3 types of markers
greenIcon
yellowIcon
redIcon
The color of the marker corresponds with the row result. If the result value in the csv is AV then the marker should be greenIcon. That's the idea.
Than you for, looking forward to your suggestions!
You are close. First you need a ternary or an if statement to check csv's result value as you mention when instantiating a marker. It accepts an object which has some options including icon key. Using that you can define a different icon apart from the predefined
for (var i in data) {
var row = data[i];
const marker = L.marker([row.lat, row.long], {
icon: row.result === "AV" ? greenIcon : blueIcon
})
.addTo(map)
.bindPopup(row.display_na)
.openPopup();
}
Moreover your csv should be in the form of:
result,display_na,lat,long
AV,14 Amsterdamer Straße Leopoldkiez Wedding Mitte Berlin 13347 Deutschland,52.5517197,13.3574034
VK,Seestraße Wedding Mitte Berlin 13351 Deutschland,52.541301,13.3341968
You need to have commas only when separating each column values otherwise it is considered a different column value.
Demo

Sort JSON array by timestamp, extract key/value pairs and write to google sheet

I am trying to take info from a JSON array in a Google Sheet and take the last chronological entry in the array and copy it into the two adjacent columns
The data I want is in Column L of my sheet (starting in row 2) and in the format:
[{"id": "XX:123456", "timestamp": "2020-01-27T19:25:51.303"}, {"id": "XX:654321", "timestamp": "2020-01-27T19:40:37.06"}]
var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("data");
var dataRange = sheet.getDataRange();
var lastRow = dataRange.getLastRow();
function parseData() {
let parseRange = sheet.getRange(1+1,11,lastRow-1,1); //col L
let values = parseRange.getValues();
let out = values.map(([row])=>{
let {id, timestamp} = JSON.parse(row).pop();
return [id, timestamp];
});
sheet.getRange(1+1, 12, lastRow-1, 2).setValues(out);
}
This is extracting data from the array, however since the JSON itself is not sorted, I need to ensure it is taking the id, and timestamp for the object with the latest timestamp chronologically
Use .reduce to find the latest:
let {id, timestamp} = JSON.parse(row).reduce(
(a,c) => a.timestamp > c.timestamp ? a : c //lexigographic enough for iso8601
)

Take keys from Dictionary and map them to an array

I'm trying to build a closure that does what my title says. My code runs but it does not print what I expected.
var names: [String] = []
var namesAndAges = ["Tom": 25, "Michael": 35, "Harry": 28, "Fabien": 16]
var ofAge = namesAndAges.filter { namesAndAges in namesAndAges.value > 18 }
var addNames = ofAge.map { ofAge in names.append(ofAge.key) }
print(addNames) //this prints [(), (), ()]
Basically you are misusing filter and map methods.
Try this:
var names: [String] = []
var namesAndAges = ["Tom": 25, "Michael": 35, "Harry": 28, "Fabien": 16]
var ofAge = namesAndAges.filter { $0.value > 18 }
var addNames = ofAge.map { $0.key }
print(addNames) //this prints ["Michael", "Harry", "Tom"]
The issue you're experience is because names.append(ofAge.key) returns Void (a.k.a. the empty tuple, ()). map produces a new Array containing the return values of the given closure after it's been applied to every element of the source array (ofAge, in your example).
The names array will actually contain the data you want, but this isn't how map is meant to be used (you're essentially using it in place of forEach).
Try this instead:
var namesAndAges = ["Tom": 25, "Michael": 35, "Harry": 28, "Fabien": 16]
var namesOfAge = namesAndAges.filter { $0.value > 18 }.map{ $0.key }
print(namesOfAge)
To avoid looping more than once, this is how I do it:
var namesAndAges = ["Tom": 25, "Michael": 35, "Harry": 28, "Fabien": 16]
let addNames: [String] = namesAndAges.flatMap { $0.value > 18 ? $0.key : nil }
print(addNames) // prints ["Michael", "Harry", "Tom"]
(oh and it's shorter 🙃)

Compare Two Arrays, Get Uncommon Values

I have a simple problem that I'm having trouble thinking around:
var oldValues : Array = [ 4, 5, 6 ];
var newValues : Array = [ 3, 4, 6, 7 ];
I want to get the values from newValues that aren't in oldValues - 3, 7
I want to get the values from oldValues that aren't in newValues - 5
A way of getting both sets of values together would be nice as well - 3, 5, 7
I can only think of convoluted methods for each by using nested loops that do a lot of redundant checking. Can someone suggest something more clean? Thanks.
You need a bunch of loops, but you can optimize them and totally avoid nested loops by using a lookup object.
var oldValues : Array = [ 4, 5, 6 ];
var newValues : Array = [ 3, 4, 6, 7 ];
var oldNotInNew:Array = new Array();
var newNotInOld:Array = new Array();
var oldLookup:Object = new Object();
var i:int;
for each(i in oldValues) {
oldLookup[i] = true;
}
for each(i in newValues) {
if (oldLookup[i]) {
delete oldLookup[i];
}
else {
newNotInOld.push(i);
}
}
for(var k:String in oldLookup) {
oldNotInNew.push(parseInt(k));
}
trace("Old not in new: " + oldNotInNew);
trace("new not in old: " + newNotInOld);
Results:
Old not in new: 5
new not in old: 3,7
var difference : Array = new Array();
var i : int;
for (i = 0; i < newValues.length; i++)
if (oldValues.indexOf(newValues[i]) == -1)
difference.push(newValues[i])
trace(difference);
use casa lib
main page:http://casalib.org/
doc: http://as3.casalib.org/docs/
list class: http://as3.casalib.org/docs/org_casalib_collection_List.html
removeItems http://as3.casalib.org/docs/org_casalib_collection_List.html#removeItems
clone the list, and use newValues.removeItems(oldValues) to get the values from newValues that aren't in oldValue
and then use the same way to get the values from oldValues that aren't in newValue
concat the previous two results
There will be no looping in your code... Although there will be looping inside the code of list class :D

Resources