I need help splitting an array - javascript

I am having a difficult time editing this script. It looks at one tab, pulls all rows that meet the criteria and pastes them into another tab. The script below works, but doesn't quite fit my needs. It is pasting the entire row, I only need Columns A,B and C. Ideally, I would need the data copied into Columns A,D and E respectively. Thanks for any help!
function Migrate2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('OnBoard');
var targetSheet = ss.getSheetByName('NewHire');
var val = sheet.getRange('a3:l').getValues();
var headers = val.shift();
var arr = [],
rowsToWriteBack = [];
rowsToWriteBack.push(headers);
val.forEach(function (r, i) {
r[7] == 'COMPLETE'&& r[11] == 'N' ? arr.push(r) : rowsToWriteBack.push(r)});
if (arr.length > 0) {
targetSheet.getRange(targetSheet.getLastRow() + 1, 1, arr.length, arr[0].length).setValues(arr);
}
}

Try this
function Migrate2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('OnBoard');
var targetSheet = ss.getSheetByName('NewHire');
var val = sheet.getRange('a3:l').getValues();
var headers = val.shift();
var arr = [],
rowsToWriteBack = [];
rowsToWriteBack.push(headers);
val.forEach(function (r, i) {
r[7] == 'COMPLETE'&& r[11] == 'N' ?
arr.push([r[0],r[1],r[2]]) :
rowsToWriteBack.push([r[0],r[1],r[2]])
});
if (arr.length > 0) {
for(var i = 0; i < arr.length; i++) {
targetSheet.getRange(targetSheet.getLastRow() + i + 1, 1, 1, 1).setValues(arr[i][0]);
targetSheet.getRange(targetSheet.getLastRow() + i + 1, 4, 1, 1).setValues(arr[i][1]);
targetSheet.getRange(targetSheet.getLastRow() + i + 1, 5, 1, 1).setValues(arr[i][2]);
}
}
}
}
Hard to test without access to the environment you're working in, but I think the above should work. Good luck!
Here's the updated version that (hopefully) fixes the staggering issue:
function Migrate2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('OnBoard');
var targetSheet = ss.getSheetByName('NewHire');
var val = sheet.getRange('a3:l').getValues();
var headers = val.shift();
var arr = [],
rowsToWriteBack = [];
rowsToWriteBack.push(headers);
val.forEach(function (r, i) {
r[7] == 'COMPLETE'&& r[11] == 'N' ?
arr.push([r[0],r[1],r[2]]) :
rowsToWriteBack.push([r[0],r[1],r[2]])
});
if (arr.length > 0) {
for(var i = 0; i < arr.length; i++) {
var addToRow = targetSheet.getLastRow() + i + 1;
targetSheet.getRange(addToRow, 1, 1, 1).setValues(arr[i][0]);
targetSheet.getRange(addToRow, 4, 1, 1).setValues(arr[i][1]);
targetSheet.getRange(addToRow, 5, 1, 1).setValues(arr[i][2]);
}
}
}
}
attempt #3 to prevent the row skipping
function Migrate2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('OnBoard');
var targetSheet = ss.getSheetByName('NewHire');
var startingRow = targetSheet.getLastRow() + 1;
var val = sheet.getRange('a3:l').getValues();
var headers = val.shift();
var arr = [],
rowsToWriteBack = [];
rowsToWriteBack.push(headers);
val.forEach(function (r, i) {
r[7] == 'COMPLETE'&& r[11] == 'N' ?
arr.push([r[0],r[1],r[2]]) :
rowsToWriteBack.push([r[0],r[1],r[2]])
});
if (arr.length > 0) {
for(var i = 0; i < arr.length; i++) {
var addToRow = startingRow + i;
targetSheet.getRange(addToRow, 1, 1, 1).setValues(arr[i][0]);
targetSheet.getRange(addToRow, 4, 1, 1).setValues(arr[i][1]);
targetSheet.getRange(addToRow, 5, 1, 1).setValues(arr[i][2]);
}
}
}
}

Related

How can I push another value in the duplicate value of the array?

How can I push another value in the duplicate value of the array?
const numArr = [0,5,5,5,1,1,0,0,0,3,3,6,6,6];
const colArr = ['red','blue','yellow']
Here, I would like to get the following results.
const result = [0,'red','red','red','blue','blue',0,0,0,'yellow','yellow','red','red','red'];
I did like this, but I don't know how to loop the colArr.
const numArr = [0,5,5,5,1,1,0,0,0,3,3,6,6,6];
const colArr = ['red','blue','yellow']
function solution(numArr , colArr) {
const answer = [];
for(let i = 0; i < numArr.length; i++) {
const arrElem = numArr[i];
if(arrElem == 0) {
answer.push(0);
} else {
answer.push("red")
}
}
return answer;
}
console.log(solution(numArr , colArr))
// The results should be like this..
// answer = [0,'red','red','red','blue','blue',0,0,0,'yellow','yellow','red','red','red'];
If you return into the loop, your array answer won't be fulled.
You cannot modify a constant value. Replace const with var
var numArr = [0, 5, 5, 5, 1, 1, 0, 0, 0, 3, 3, 6, 6, 6];
var colArr = ['red','blue','yellow']
console.log(solution(numArr , colArr));
function solution(numArr , colArr) {
var answer = [];
var lastElem = null;
var lastIndexColor = null;
for(let i = 0; i < numArr.length; i++) {
var arrElem = numArr[i];
if(arrElem == 0) {
answer.push(arrElem);
}
else{
if(lastElem == arrElem){
answer.push(colArr[lastIndexColor % colArr.length]);
}
else{
if(lastIndexColor == null){
lastIndexColor = 0;
answer.push(colArr[lastIndexColor % colArr.length]);
}
else{
lastIndexColor++;
answer.push(colArr[lastIndexColor % colArr.length]);
}
}
}
lastElem = arrElem;
}
return answer;
}

How to compare Sheet Names with Array elements and execute tasks on Google Sheets using script?

The goal is to get each sheet name and check if it's not in the array. If not, then certain ranges are copied into a "database" sheet and then compare the next sheet and so on.
The problem is that itis comparing, it is giving me -1 as the result and it is executing the tasks, when it shouldn't be and I can't see where the flaw is.
Here's the code:
function concatenarResumos() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var databaseSheet = ss.getSheetByName("Database");
var processedSheetsRng = ss.getSheetByName("Suporte").getRange("F6:F").getValues().flat();
var shts = ss.getSheets();
for (var j = 0; j < shts.length; j++) {
for (var n = 0; n < processedSheetsRng.length; n++) {
if (processedSheetsRng[n].indexOf(shts[j].getSheetName() === -1)) {
shts[j].activate;
var sheetName = shts[j].getSheetName();
Logger.log("Sheet Name: " + sheetName);
Logger.log("Processed Sheet Name: " + processedSheetsRng[n])
var data = shts[j].getRange("C4").getValue();
var naoConforme = shts[j].getRange("B8:G12").getValues();
shts[j].getRange("B8:G12").copyTo(databaseSheet.getRange(databaseSheet.getLastRow() + 1, 2, 6, naoConforme.length), { contentsOnly: true });
var targetCol = databaseSheet.getRange('A:A').getValues();
var maxIndex = targetCol.reduce(function (maxIndex, row, index) {
return row[0] === "" ? maxIndex : index;
}, 0);
databaseSheet.getRange(maxIndex + 2, 1, naoConforme.length, 1).setValue(data);
}
}
}
Here is the logger output:
function concatenarResumos() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const dsh = ss.getSheetByName("Database");
const ssh = ss.getSheetByName("Suporte");
const svs = ssh.getRange(6, 6, sh.getLastRow() - 5).getValues().flat();
const shts = ss.getSheets();
for (let j = 0; j < shts.length; j++) {
for (let n = 0; n < svs.length; n++) {
if (~svs[n].indexOf(shts[j].getName())) {
let d1 = shts[j].getRange("C4").getValue();
shts[j].getRange("B8:G12").copyTo(dsh.getRange(dsh.getLastRow() + 1, 2, 6, d2.length), { contentsOnly: true });
let tcol = dsh.getRange(1, 1, dsh.getLastRow()).getValues();
let maxIndex = tcol.reduce(function (maxIndex, row, index) {return row[0] === "" ? maxIndex : index;}, 0);
dsh.getRange(maxIndex + 2, 1, d2.length, 1).setValue(d1);
}
}
}
Ranges like F6:F & A:A are bad to use with google apps script because they create a lot of nulls at the end of the array which need to get filtered out.

Clear matching cells on different tables (Unordered columns)

so... i got a problem on comparing different tables contents.
I basically need to clear the content where the cells data is the same, but the tables are unordered, and when i run my code, only the first line is cleared.
So i modified from this (Because it was clearing only the first line of the table):
function clearSourceValues(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourceTable = ss.getSheetByName("Encaminhamento");
var targetTable = ss.getSheetByName("testeBD");
var rowCount = targetTable.getLastRow() + 1;
var sourceValues = sourceTable.getRange(2, 8, rowCount, 1).getValues();
var targetValues = targetTable.getRange(2, 3, rowCount, 1).getValues();
for (var i = 0; i < targetValues.length; i++){ // Modified
var clearRange = targetTable.getRange(i + 2, 2, 1, 8); // Modified
if (targetValues[i][0] == sourceValues[i][0]){
clearRange.clear();
};
};;
};
To this:
for (var i = 0; i < targetValues.length; i++){
var clearRange = targetTable.getRange(i + 2, 2, 1, 8);
for (var j = 0; j < sourceValues.length; j++){
if (targetValues[i][0] == sourceValues[j][0]){
clearRange.clear();
};
};
};
But now when i run it, every cells are cleared.
Clearing Source and Destination Ranges on a match in columns 3 of source and 8 of destination
function clearSourceandDestinationValues(){
var ss=SpreadsheetApp.getActive();
var ssh=ss.getSheetByName("Encaminhamento");
var tsh=ss.getSheetByName("testeBD");
var srg=ssh.getRange(2,8,ssh.getLastRow()-1,1);
var trg=tsh.getRange(2,3,tsh.getLastRow()-1,1);
var svA=srg.getValues();
var sA=svA.map(function(r){return r[0]});//flatten
var tvA=trg.getValues();
var tA=tvA.map(function(r){return r[0]});//flatten
svA.forEach(function(r,i){if(tA.indexOf(r[0])!=-1) {ssh.getRange(i+2,1,1,ssh.getLastColumn()).clear();}});//clears source range
tvA.forEach(function(r,i){if(sA.indexOf(r[0])!=-1) {tsh.getRange(i+2,1,1,tsh.getLastColumn()).clear();}});//clears destination range
}
map function is good to use
function clearSourceValues() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourceTable = ss.getSheetByName("Encaminhamento");
var targetTable = ss.getSheetByName("testeBD");
var sourceValues = sourceTable.getRange(2, 8, (targetTable + 1), 1).getValues();
var targetValues = targetTable.getRange(2, 3, (targetTable + 1), 1).getValues();
var mapSourceTable = sourceValues.map(function(r) {
return r[5]
}) //this return you the whole data in the column "f"
var mapTargetTable = targetValues.map(function(r) {
retunrn r[0]
}); //this return you the whole data in the column "a"
for (var i = 1; /*remove the header*/ i < mapSourceTable.length; i++) {
var eltToCompare = mapSourceTable[i];
mapSourceTable.forEach(function(elt, index) {
//remove the header
if (index > 0) {
if (eltToCompare == elt) {
targetTable.deleteRow(index + 2);
}
}
});
}

What am I doing wrong to find element occurring most in array?

I am trying to debug one online coding platform problem. The problem I am facing is to return element occurring most often in array. I am interested in correcting my current code than trying other methods.
function findMostOccured(M, A) { //value of elements in A should not be greater than M
var N = A.length;
var count = new Array(M + 1);
var i;
for (i = 0; i <= M; i++)
count[i] = 0;
var maxOccurence = 1;
var index = -1;
for (i = 0; i < N; i++) {
if (count[A[i]] > 0) {
var tmp = count[A[i]];
if (tmp > maxOccurence) {
maxOccurence = tmp;
index = i;
}
count[A[i]] = tmp + 1;
} else {
count[A[i]] = 1;
}
}
return A[index];
}
Given M = 3 and A = [1, 2, 3, 3, 1, 3, 1]. It should return 3 or 1.
var arr = [1, 2, 3, 3, 1, 3, 1];
var M = 3;
function findMostOccured(M, arr) {
var obj = {};
var result = [];
for (let i = 0; i < arr.length; i++) {
if (obj[arr[i]]) {
obj[arr[i]] = obj[arr[i]] + 1;
} else {
obj[arr[i]] = 1;
}
}
for (var key in obj) {
if (obj[key] === M) {
result.push(parseInt(key));
}
}
return result;
}
console.log(findMostOccured(3, arr));

How do I prevent the contents of .join() from being added after the last value of my array?

var a = 0;
var b = 0;
var c = 0;
var d = 0;
var e = 0;
var f = 0;
var alphaA = $("#inOne").val();
var alphaB = $("#inTwo").val();
var betaA = parseFloat(alphaA);
var betaB = parseFloat(alphaB);
var numa = Math.abs(betaA);
var numb = Math.abs(betaB);
var factorA = [];
var factorB = [];
var commonFactor = [];
for (d = 0; d <= b; d++){
for (e = 0; e <= c; e++){
if (factorA[d] == factorB[e]) {
commonFactor[f] = factorA[d];
f++;
}
}
}
f--;
document.getElementById("cF").innerHTML = "Common Factors: " + commonFactor.join(", ");
If the values of my array are [1, 2, 4], the output is
Common Factors: 1, 2, 4,
How do I stop the ", " from appearing after the 4 How do I make it look like: 1, 2, 4
Try this:
[1, 2, 4, undefined, null].filter(e=>!!e).join(", ");
join() does not insert anything after the last character. Here is an example of separating each character in a string with underscore ("_"). It adds underscore after every character, but not after last character.
var str = "this is to explain join";
document.getElementById("output").textContent = str.split('').join('_');
<div id="output">
</div>

Categories

Resources