I would like to remove the values after the first comma. It is possible that there will be more values and commas.
Expected result:
8-1
10-1
2-5
5-8
ss from Logger.log for var Id
function myFunction() {
var Sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var FirstRow = 7;
var LastRow = Sheet.getLastRow();
var RowRange = LastRow - FirstRow + 1;
var WholeRange = Sheet.getRange(FirstRow,3,RowRange,9);
var AllValues = WholeRange.getValues();
for (var i=0;i<AllValues.length;i++){
var CurrentRow = AllValues[i];
var Id = CurrentRow[0]; //col with ID Sheet1
var firstId = Id.map(vA=>[vA.split(',')[1]]);
}
}
Explanation:
You can use the split method and map to apply this operation for all the input data and get the first [0] element of the resulting array:
data.map(vA=>[vA.split(',')[0]])
Code snippet:
function myFunction() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1');
const avals = sh.getRange('A1:A4').getValues().flat();
const bvals = avals.map(vA=>[vA.split(',')[0]]);
sh.getRange(1,2,bvals.length,1).setValues(bvals);
}
Sheet used for code snippet:
Make sure you format the input text as plain text, otherwise google sheets consider the input data to be dates or alternatively use getDisplayValues() instead of getValues() but I guess you have already figured out that part because console.log returns the correct input.
Updated answer based on your edited question:
Modify your current for loop as follows:
for (var i=0;i<AllValues.length;i++){
var CurrentRow = AllValues[i];
var Id = CurrentRow[0]; //col with ID Sheet1
var newId = Id.split(',')[0];
console.log(newId);
}
Related
I'm trying to achieve the following result:
So if column A has duplicate values, I want to show these duplicate values on column B. Here is what I have tried so far. But the code just makes Apple to show two times in a column B. How would I need to alter my code to make it work the way I want?
function findDuplicates() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet = ss.getActiveSheet()
var lastRow = sheet.getLastRow()
var data = sheet.getRange(1,1,lastRow).getValues()
var dataUnique = data.reduce(function (out, item) {
return out.concat(out.filter(function (comp) {
return item.toString() != comp.toString();
}).length ? [] : [item])
}, []);
var newValues = sheet.getRange(1,2,dataUnique.length).setValues(dataUnique)
}
This is the result when I run the code:
This is a spreadsheet created specifically to address this question. It contains the following code that will take values from A and output the result in column B:
function myFunction() {
var sheet = SpreadsheetApp.getActiveSheet();
var input = sheet.getRange('A1:A').getValues().filter(e=>e[0]).map(e=>e[0]);
var inputLower = input.map(e=>e.toLowerCase());
var output = new Array();
input.forEach(function (e,i,arr){if(inputLower.indexOf(e.toLowerCase())!=i && output.indexOf(e)==-1){output.push(e)}});
sheet.getRange(1,2,output.length,1).setValues(output.map(e=>[e]));
}
I want to create a new worksheet each time I have a new user details in column 1 of my USERS sheet. Here is the code I have so far:
// Get the data from the sheet called CreateSheets
var sheetNames = SpreadsheetApp.getActive().getSheetByName("USERS").getDataRange().getValues();
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("USERS");
var data = ss.getDataRange().getValues();
var lr = ss.getLastRow();
var dataRange = ss.getRange(1, 1, lr, 1);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
// For each row in the sheet, insert a new sheet and rename it.
sheetNames.forEach(function(row) {
var sheetName = data;
var sheet = SpreadsheetApp.getActive().insertSheet();
sheet.setName(sheetName);
});
}}
The code works but it is combining the data in the cells in column 1 into the name of the new spreadsheet. Thanks
function myfunc() {
const ss = SpreadsheetApp.getActive();
const ush = ss.getSheetByName("USERS");
const names = ush.getRange(1, 1, ush.getLastRow(), 1).getValues().flat();
const enames = ss.getSheets().map(s => s.getName());
names.forEach(n => {
if (~e.names.indexOf(n)) {
ss.insertSheet().setName(n);
enames.push(n); //add name to array to avoid duplicate names in column
}
});
}
Updated to account for existing sheet names and potential duplicate names in column 1.
I think this should do what you want. You should probably build in some sort of check to ensure the sheet doesn't already exist.
function makeSheetHappen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var wsUser = ss.getSheetByName("USERS");//the sheet with users
//this gets all values in column 1 to end of spreadsheet (it might include blanks)
//flat function avoids having to pull 2-dim array (h/t COOPER!)
var sheetNames = wsUser.getRange(1, 1, wsUser.getLastRow(), 1).getValues().flat();
//mapping function to get an array of the spreadsheet's sheet names.
var theExistingNames = ss.getSheets().map(function (aSheet) {
return aSheet.getName();
});
//loops through the sheetNames and ensures not blank and not currently existing.
sheetNames.forEach(function (aName) {
if (aName != '' && !theExistingNames.includes(aName)) {
var newSheet = ss.insertSheet();
newSheet.setName(aName);
theExistingNames.push(aName); //add name to array to avoid duplicate names in column
}
});
}
I have two functions in a google sheet that are meant to loop through a single column containing the file IDs of files in google drive, issuing a Properties.get to retrieve a single property "LastReview" for each document and paste all of the LastReview times in the next available column.
I'm having trouble getting the loop in "loopForMetadata" to work. I want it to acquire a list of all the LastReview times associated with each fileID and then post that to the next available column so that all of the LastReview times align with the fileIDs.
function getProperty(fileId) {
var propertyKey = 'LastReview'
var fileId = '1UaQkJU8r1kE9sxpFg6OD8aOuUCoRnSpB9Agg_R9HJ3s'
var response = JSON.stringify(Drive.Properties.get(fileId, 'LastReview', { visibility: 'PUBLIC' }).value);
var key = "value";
var resposeNoQuote = response.replace(/\"/g, "")
Logger.log(resposeNoQuote);
}
function loopForMetadata() {
var columnNeeded, data, lastColumn, sh;
sh = SpreadsheetApp.getActiveSheet();
lastColumn = sh.getLastColumn();
data = sh.getRange(1, 1, 1, lastColumn).getValues();//Get 2D array of all values in row one
data = data[0];//Get the first and only inner array
columnNeeded = data.indexOf('ID') + 1;//Arrays are zero indexed- add 1
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var rangeData = sheet.getDataRange();
var lastColumn = rangeData.getLastColumn();
var lastRow = rangeData.getLastRow();
var searchRange = sheet.getRange(2, columnNeeded, lastRow - 1, 1);
// Get array of values in the search Range
var rangeValues = searchRange.getValues();
// Loop through array and if condition met, add relevant
// background color.
var resultValues = []
for (i = 0; i < rangeValues.length; i++) {
resultValues.push(getProperty(rangeValues[i]));
Utilities.sleep(10);
}
Logger.log(resultValues);
};
I believe your goal as situation as follows.
You want to retrieve the values using the key of LastReview in the property from the files of fileId.
You want to put the retrieved values to the same row of fileId in the next available column.
You want to achieve this using Google Apps Script.
Modification point:
In your script,
getProperty() doesn't return the values.
resultValues is not put to the Spreadsheet.
When you want to retrieve the value of the key LastReview, Drive.Properties.get(fileId, 'LastReview', { visibility: 'PUBLIC' }).value directly returns the value.
As an important point, when the file of fileId has not property of the key LastReview, it seems that Drive.Properties.get() occurs an error. So in this modification, as a simple workaround, I used the try catch.
When above points are reflected to your script, it becomes as follows.
Sample script:
function loopForMetadata() {
var columnNeeded, data, lastColumn, sh;
sh = SpreadsheetApp.getActiveSheet();
lastColumn = sh.getLastColumn();
data = sh.getRange(1, 1, 1, lastColumn).getValues();//Get 2D array of all values in row one
data = data[0];//Get the first and only inner array
columnNeeded = data.indexOf('ID') + 1;//Arrays are zero indexed- add 1
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var rangeData = sheet.getDataRange();
var lastColumn = rangeData.getLastColumn();
var lastRow = rangeData.getLastRow();
var searchRange = sheet.getRange(2, columnNeeded, lastRow - 1, 1);
var rangeValues = searchRange.getValues();
var resultValues = []
// I modified below script.
for (i = 0; i < rangeValues.length; i++) {
var fileId = rangeValues[i];
var value = "";
try {
value = Drive.Properties.get(fileId, 'LastReview', { visibility: 'PUBLIC' }).value;
} catch(e) {}
resultValues.push([value]);
// Utilities.sleep(10); // I'm not sure whether this is required.
}
sheet.getRange(2, lastColumn + 1, resultValues.length, 1).setValues(resultValues);
Logger.log(resultValues);
};
Note:
Please confirm whether Drive API is enabled at Advanced Google services, again.
Reference:
Properties: get
I have an array within a spreadsheet that has stock data. I want to find a column number "restock value", and the row number product/sku (Row) to eventually build a custom function. The column is indexing fine, but the Row keeps logging 0.
I've tested a few objects within my array. I've also tried removing the column index. but no dice. still logging 0.
I've also tried removing [0] from my code. It seems that this is part of the problem, because when I log lookupRowValues without [0] I get the value of each row with their own individual brackets, when I add [0] I only log the first row.
function UnitsToShip(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("US");
//Lookup Column
var lc = ss.getLastColumn();
var lookupColumnValues = ss.getRange(4,2,1,lc).getValues()[0];
var indexColumn = lookupColumnValues.indexOf("Restock Amount") + 1;
//Lookup Row
var lr = ss.getLastRow();
var lookupRowValues = ss.getRange(4,2,lr,1).getValues()[0];
var indexRow = lookupRowValues.indexOf("AH-POR-DIF-WHT")+1;
Logger.log(indexRow);
}
I'm testing it with a product in the array that should return 6.
Try this:
function UnitsToShip(){
var ss=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("US");
//Lookup Column
var lc = ss.getLastColumn();
var lookupColumnValues = ss.getRange(4,2,1,lc-1).getValues()[0];
var indexColumn = lookupColumnValues.indexOf("Restock Amount") + 2;
Logger.log('indexColumn: %s',indexColumn);
//Lookup Row
var lr = ss.getLastRow();
var lookupRowValues = ss.getRange(4,2,lr-3,1).getValues().map(function(r){return r[0];});
var indexRow = lookupRowValues.indexOf("AH-POR-DIF-WHT")+4;
Logger.log('indexRow: %s',indexRow);
var restockAmount=ss.getRange(indexRow,indexColumn).getValue();
Logger.log('Restock Amount: %s',restockAmount);
}
I need a help reading cell value using either java or google script. The cell I am trying to read has a formula. When my script reads the data I get #DIV\0! error.
here is my simple script:
function readData(){
var Keys = "1Vp_fjFVFXHDjJRXl7C6mNzCK66jVB1I1BjieaZK6P";
var SheetName = "AAL";
var WR;
SS = SpreadsheetApp.openById(Keys);
Sheet = SS.getSheetByName(SheetName);
Range = Sheet.getDataRange();
Data = Range.getValues();
WR = Data[30][15];
}
Any help will be appriciated, Thanks.
Instead of doing [30][15], use this code to limit the range to one cell.
If that doesn't work, maybe your cell actually contains this DIV/0 value?
function readData(){
var Keys = "1Vp_fjFVFXHDjJRXl7C6mNzCK66jVB1I1BjieaZK6P";
var SheetName = "AAL";
var WR;
SS = SpreadsheetApp.openById(Keys);
Sheet = SS.getSheetByName(SheetName);
Range = Sheet.getRange(30, 15); //changed here
Data = Range.getValue(); //and here
WR = Data; //and here
}