Trying to understand logic behind map method - google-apps-script

I am trying to understand the logic of using array methods within Map functions (such as push, slice, etc). Below, I have a function that is trying to add an element in the middle of a 2D array, but it comes out completely blank. Not sure what I am missing
function array () {
let numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
// Attempted outcome = [[1, 2, "Hello", 3], [4, 5, "Hello", 6], [7, 8, "Hello", 9]]
let newNumbers = numbers.map(function (row) {
return [row.slice(2, 0, "Hello")]
})
Logger.log(newNumbers);
}

In your script, how about the following modification?
From:
let newNumbers = numbers.map(function (row) {
return [row.slice(2, 0, "Hello")]
})
To:
let newNumbers = numbers.map(function (row) {
row.splice(2, 0, "Hello");
return row;
});
or, in this case, the following modification might be able to be used.
let newNumbers = numbers.map(([a, b, ...c]) => [a, b, "Hello", ...c]);
Testing:
let numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
// Attempted outcome = [[1, 2, "Hello", 3], [4, 5, "Hello", 6], [7, 8, "Hello", 9]]
let newNumbers = numbers.map(function (row) {
row.splice(2, 0, "Hello");
return row;
});
console.log(newNumbers);
Reference:
splice()

Related

Hide an array of columns in Google App Scripts

Beginner programmer here, apologies in advance if my vocabulary is not really accurate while explaining my issue.
I have a script that creates a custom menu (view) and hides different set of columns based on the view you want to see.
How can I change the script so instead of typing all my columns I can get an array of columns (in this case array [1 to 4] and [7 to 13])?
Below the particular section of my code that I'd like to change
function hideColumnsAll30() {
const obj = [{ sheetName: "Planning / Tracking", hide: [1, 2, 3, 4, 7, 8, 9, 11, 12, 13 ] }, { sheetName: "Resources", hide: [2, 4, 5, 9]}, {sheetName: "Documentation", hide:[2, 4, 5, 9]} ];
sample_(obj);
}
And here is the full script if it helps solving my issue
function onOpen() {
const ui = SpreadsheetApp.getUi();
ui.createMenu('Custom View')
.addItem('All - 30 days', 'hideColumnsAll30')
.addItem('All - 1 year', 'hideColumnsAll1y')
.addItem('Unhide All', 'showColumns')
.addToUi();
function showColumns() {
const sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
showColumnsInAllSheets_(sheets);
}
function hideColumnsAll30() {
const obj = [{ sheetName: "Planning / Tracking", hide: [1, 2, 3, 4, 7, 8, 9, 11, 12, 13 ] }, { sheetName: "Resources", hide: [2, 4, 5, 9]}, {sheetName: "Documentation", hide:[2, 4, 5, 9]} ];
sample_(obj);
}
function hideColumnsAll1y() {
const obj = [{ sheetName: "Planning / Tracking", hide: [1, 3, 4, 5, 6, 7, 8, 9, 11, 12, ] }, { sheetName: "Resources", hide: [2, 4, 5, 9]}, {sheetName: "Documentation", hide:[2, 4, 5, 9]} ];
sample_(obj);
}
Thanks in advance for your help!
From your following replying,
I need to type all the columns manually -> [1, 2, 3, 4, 7, 8, 9, 10, 11, 12, 13] I would like to have 2 arrays, like this -> [1 - 4], [7 -13]
I guessed that you wanted to retrieve an array of [1, 2, 3, 4, 7, 8, 9, 10, 11, 12, 13] by using 2 arrays like [1 - 4], [7 -13]. If my understanding is correct, how about the following sample script?
Sample script:
const input = [[1, 4], [7, 13]]; // 1st and 2nd element of each array are start and end values, respectively.
const res = input.flatMap(([start, end]) => [...Array(end)].map((_, i) => i + 1).slice(start - 1, end));
console.log(res);
When this script is run, an array of [ 1, 2, 3, 4, 7, 8, 9, 10, 11, 12, 13 ] is obtained.
References:
map()
flatMap()
Added:
From your following reply,
I actually found similar piece of code to add to my script online. However it does not fit my case as I need to give the name of each sheets where I want to hide columns.
And, in your provided script, I found the following message.
I have other speadsheets with 1000+ columns, so I cannot hide them manually from 1 to 1000. This is the reasons why I'm trying to include several arrays in my script
In this case, is the following script your expected script?
const columns = input => input.flatMap(([start, end]) => [...Array(end)].map((_, i) => i + 1).slice(start - 1, end));
function hideColumnsAll30() {
const obj = [{ sheetName: "Planning / Tracking", hide: columns([[1, 4], [7, 13]]) }, { sheetName: "Resources", hide: [2, 4, 5, 9]}, {sheetName: "Documentation", hide:[2, 4, 5, 9]} ];
sample_(obj);
}
At hide: columns([[1, 4], [7, 13]]), hide: [ 1, 2, 3, 4, 7, 8, 9, 10, 11, 12, 13 ] is created.
Suggestion
In your script I am not sure where you will use the arrays 1-4 and 7-13 since in the scripts specially on the part { sheetName: "Planning / Tracking", hide: [1, 2, 3, 4, 7, 8, 9, 11, 12, 13 ] } you are skipping number 10 here and on the other function you skipped 2.
Here's a suggestion on how you can use an array to your function. You can just add a new variable outside the functions to make it global variables, here is where you will insert the array values you want. You can then access these variables in any of your functions so you only have to edit one line in case you will adjust the columns.
Try this code:
function onOpen() {
const ui = SpreadsheetApp.getUi();
ui.createMenu('Custom View')
.addItem('All - 30 days', 'hideColumnsAll30')
.addItem('All - 1 year', 'hideColumnsAll1y')
.addItem('Unhide All', 'showColumns')
.addToUi();
};
//Declare arrays here***
//Put in array the columns for Resources and Documentation sheets
var resDocArray = [2,4,5,9];
//Put in array the columns for the planning/tracking tab for 2 different functions
var colAll30d = [1, 2, 3, 4, 7, 8, 9, 11, 12, 13];
var colAll1y = [1, 3, 4, 5, 6, 7, 8, 9, 11, 12]
//***
function showColumns() {
const sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
showColumnsInAllSheets_(sheets);
};
function hideColumnsAll30() {
const obj = [{ sheetName: "Planning / Tracking", hide: colAll30d }, { sheetName: "Resources", hide: resDocArray}, {sheetName: "Documentation", hide:resDocArray} ];
sample_(obj);
};
function hideColumnsAll1y() {
const obj = [{ sheetName: "Planning / Tracking", hide: colAll1y }, { sheetName: "Resources", hide: resDocArray}, {sheetName: "Documentation", hide:resDocArray} ];
sample_(obj);
};
function sample_(obj) {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheets = ss.getSheets();
showColumnsInAllSheets_(sheets);
const sheetObj = sheets.reduce((o, s) => (o[s.getSheetName()] = s, o), {});
obj.forEach(({ sheetName, hide }) => {
if (sheetObj[sheetName]) {
hide.forEach(h => sheetObj[sheetName].hideColumns(h, 1));
}
});
};
function showColumnsInAllSheets_(sheets) {
sheets.forEach(s => s.showColumns(1, s.getMaxColumns()));
};
You can also add the arrays the way Tanaike suggested.
Let me know if this helps!
Reference:
Hide columns in multiple sheets

How to create chart using Springboot Json api

i have this service that give back this Json result :
{
"MANNOUBA": 1,
"Medinine": 4,
"Gabes": 5,
"Tunis": 22,
"Beja": 3,
"Kebili": 0,
"Sfax": 11,
"Laundry Making": 6,
"italia": 0,
"Sousse": 6,
"Desk": 1,
"Jendouba": 3,
"Mahdia": 6,
"Ben Arous": 19,
"Zaghouan": 4,
"Gafsa": 0,
"Kairouan": 6,
"Monastir": 18,
"metos": 1,
"Eleonetech": 2,
"Nabeul": 22,
"Mannouba": 9,
"BENAROUS": 8,
"Ariana": 21,
"Bizerte": 3
}
i want to put this data in a Barchart For my angular Project with the names in the X axis and the Numbers in the Y axis
With using Highcharts, you can preprocess your data to the: [name, y] format and use category axis type. Example:
for (let key in data) {
chartData.push([key, data[key]]);
}
Highcharts.chart('container', {
xAxis: {
type: 'category'
},
series: [{
type: 'column',
data: chartData
}]
});
Live demo: http://jsfiddle.net/BlackLabel/cjk3uboh/
Highcharts angular wrapper: https://www.npmjs.com/package/highcharts-angular

Google Apps Script function to denormalize json data working erratically

I have a function to denormalize json data.
Json data looks like:
-entries
- entry
- skus
What I am trying to do is to create an array of objects where entries with more than 1 SKUs should be repeated the x times, where x is the number of skus (length of the sku array); each time switching the data of the skus.
The problem is that the sku data does not switch, and the same skus are shown multiple times in the resulting array.
When I debug step by step, the array is appended fine at the beginning, however when function proceeds the correctly appended elements of the array are overwritten.
Here the function code:
let data = [
{
name: 'a',
skus: [1, 2],
},
{
name: 'b',
skus: [3, 4],
},
{ name: 'c', skus: [5] },
{ name: 'd', skus: [6, 7, 8] },
];
function flatten(data) {
let newArray = [];
for (i in data) {
const el = {};
el.name = data[i].name;
let skus = data[i].skus;
for (j in skus) {
el.sku = skus[j];
newArray.push(el);
console.log(el);
}
}
return newArray;
}
what I am trying to achieve is to return a new array which is so:
[
{ name: a,
sku: 1
},
{ name: a,
sku: 2
},
{
name: b,
sku: 3,
},
{
name: b,
sku: 4,
}... and so on ]
Thanks
You want to achieve the following conversion.
From
const data = [
{name: 'a', skus: [1, 2]},
{name: 'b', skus: [3, 4]},
{name: 'c', skus: [5]},
{name: 'd', skus: [6, 7, 8]},
];
To
[
{"name": "a", "sku": 1},
{"name": "a", "sku": 2},
{"name": "b", "sku": 3},
{"name": "b", "sku": 4},
,
,
,
]
Modification points:
I think that the reason of your issue is due to the call by reference. When the object el is put to the array with newArray.push(el), el is changed by the next loop. By this, I think that your issue occurs. In this case, it is required to copy the object and put to the array.
When above points are reflected to your script, it becomes as follows.
Modified script:
From:
newArray.push(el);
To:
newArray.push(Object.assign({}, el));
Testing:
let data = [
{name: 'a', skus: [1, 2]},
{name: 'b', skus: [3, 4]},
{name: 'c', skus: [5]},
{name: 'd', skus: [6, 7, 8]},
];
function flatten(data) {
let newArray = [];
for (i in data) {
const el = {};
el.name = data[i].name;
let skus = data[i].skus;
for (j in skus) {
el.sku = skus[j];
newArray.push(Object.assign({}, el));
// console.log(el);
}
}
return newArray;
}
console.log(flatten(data))
Other pattern:
In your case, the following script can be also used.
const data = [
{name: 'a', skus: [1, 2]},
{name: 'b', skus: [3, 4]},
{name: 'c', skus: [5]},
{name: 'd', skus: [6, 7, 8]},
];
const res = data.reduce((ar, {name, skus}) => {
skus.forEach(e => ar.push({name: name, sku: e}));
return ar;
}, []);
console.log(res);
Reference:
Object.assign()

How to use of AND and OR operator in same query in sequelize?

I execute the below query but i gives error. I want the result of my SQL query which i posted at end.
userServiceAppointmentModel.findAll({
where: {
technician_id: resultsFromAuthentication.technician_id,
is_confirmed_by_user: 1,
$or: {
service_start_time: {
gte: curLocalDate
},
service_running_status: 1
}
},
attributes: attributes
}).complete(function (err, appointmentResponse) {
if (err) {
console.log(err);
}
SELECT
`id`, `technician_id`, `user_id`, `service_id`, `service_name`,
`service_location_string`, `service_location_latitude`,
`service_location_longitude`, `service_start_time`, `service_end_time`,
`notes`, `total_cost`, `service_cost`, `is_confirmed_by_user`,
`is_confirmed_by_technician`, `service_running_status`,
`service_start_time_by_technician`,`service_complete_time_by_technician`
FROM `user_service_appointment` AS `user_service_appointment`
WHERE `user_service_appointment`.`technician_id`=154
AND `user_service_appointment`.`is_confirmed_by_user`=1
AND (`user_service_appointment`.`service_start_time` >='2015-02-26 01:07'
OR `user_service_appointment`.`service_running_status`=1)
At least for the version 2.0.0 you could use Seuqlize.and and Sequelize.or
for your case
..
where: {where: Sequelize.and(
{technician_id: resultsFromAuthentication.technician_id},
{is_confirmed_by_user: 1},
Sequelize.or({
service_start_time: {
gte: curLocalDate
}},
{service_running_status: 1}
)
)
..
in new version try like this
model.update(
req.body,
{
where: { task_id: req.params.task_id,
$and: {id: 11}
$gt: {end_date: myDate}
} }
)
.then(function () {
res.status(200).json({"message":"done"})
}
)
.catch(function (err) {
})
For more detail see the Documentation
Here i want to mention some of them
$and: {a: 5} // AND (a = 5)
$or: [{a: 5}, {a: 6}] // (a = 5 OR a = 6)
$gt: 6, // > 6
$gte: 6, // >= 6
$lt: 10, // < 10
$lte: 10, // <= 10
$ne: 20, // != 20
$eq: 3, // = 3
$not: true, // IS NOT TRUE
$between: [6, 10], // BETWEEN 6 AND 10
$notBetween: [11, 15], // NOT BETWEEN 11 AND 15
$in: [1, 2], // IN [1, 2]
$notIn: [1, 2], // NOT IN [1, 2]
$like: '%hat', // LIKE '%hat'
$notLike: '%hat' // NOT LIKE '%hat'
$iLike: '%hat' // ILIKE '%hat' (case insensitive) (PG only)
$notILike: '%hat' // NOT ILIKE '%hat' (PG only)
$like: { $any: ['cat', 'hat']} // LIKE ANY ARRAY['cat', 'hat'] - also works for iLike and notLike
$overlap: [1, 2] // && [1, 2] (PG array overlap operator)
$contains: [1, 2] // #> [1, 2] (PG array contains operator)
$contained: [1, 2] // <# [1, 2] (PG array contained by operator)
$any: [2,3] // ANY ARRAY[2, 3]::INTEGER (PG only)
userServiceAppointmentModel.findAll({where: Sequelize.and(
{technician_id: resultsFromAuthentication.technician_id},
{is_confirmed_by_user: 1},
Sequelize.or({
service_start_time: {
gte: curLocalDate
}},
{service_running_status: 1}
)
)
}).complete(function (err, appointmentResponse) {

Json format issue with flot chart in asp.net mvc application

I am working on a flot chart and I am unable to covert json string to required flot graph format. Below is what I tried.
My Json
Data: [
{ "Day": 8, "Visits": 145 },
{ "Day": 7, "Visits": 26 }
];
Format I am trying to achieve: [[0, 12], [1, 2], [2, 2], [3, 3], [4, 4]];
$(document).ready(function () {
var data = [{ "Day": 8, "Visits": 145 }, { "Day": 7, "Visits": 26 }];
var dailyHits = [];
$.each(data, function (_index, _item) {
var c = [_item["Day"], _item["Visits"]];
dailyHits.push(c);
});
//var dailyHits1= [[0, 12], [1, 2], [2, 2], [3, 3], [4, 4]];
var chartData = [dailyHits];
console.log(chartData);
$.plot($("#chartHits"), chartData);
});
Any help would be highly appreciated.
Hey i have same problem and i think problem is that you get data in string format, but array should be with Integers