I'm getting the numbers in a column and subtracting 1 from it, when the value it not empty:
function myFunction(){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const colSettingSheet = ss.getSheetByName('Settings');
let colSettings = colSettingSheet.getRange('D4:E').getValues();
let indexes = colSettings.map(e => e[1] > 0 ? e[1] - 1 : e[1]).filter(e => e != '');
}
The original values:
[[6,7,8,1,,,,14,31,17,30,15,16,34]]
This is what it's returning:
[5,6,7,13,30,16,29,14,15,33]
...and it's missing a 0 between 7 and 13 and I can't find out why.
Appreciate your input!
function myFunction() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1');
let s = sh.getRange('D4:E' + sh.getLastRow()).getValues();
Logger.log(s.map(e => e[1] > 0 ? e[1] - 1 : e[1]));
}
You do not require the filter if you simply eliminate the nulls in the first place with lastRow
You need filter out undefined, not empty string.
And as Alexey Zelenin suggested, filter and map should be swapped
let colSettings = [6,0,7,8,1,,,,14,31,17,30,15,16,34].map(a => [0,a]);
let indexes = colSettings.filter(e => e !== undefined).map(e => e[1] > 0 ? e[1] - 1 : e[1]);
console.log(indexes);
filter automatically removes empty items, you can use filter(Boolean) instead.
[EDIT]
You don't really need loop twice through the array with filter and map, you can use reduce and filter it in one shot:
let colSettings = [6,0,7,8,1,,,,14,31,17,30,15,16,34].map(a => [0,a]);
let indexes = colSettings.reduce((r,a) => ((r[r.length] = a[1] - (a[1] && 1)), r), []);
console.log(indexes);
P.S.
Your original code suggests that the original array format is different then you've posted, it's more like:
[[0,6],[0,7],[0,8],[0,1],,,,[0,14],[0,31],[0,17],[0,30],[0,15],[0,16],[0,34]]
If the array is actual in format you've posted [[6,7,8,1,,,,14,31,17,30,15,16,34]] than the code for that would be:
let colSettings = [[6,0,7,8,1,,,,14,31,17,30,15,16,34]];
let indexes = colSettings.map(ar => ar.reduce((r,a) => ((r[r.length] = a - (a && 1)), r), []));
console.log(indexes);