[英]Compare each element of one array to another and find which element is not found
[英]How to increment each string element from one array that is found in another array?
我有点陷入这个问题,目标是从 B 列中的 A 列中找到匹配值,并仅在 B 列中将相同的值增加 1,这适用于单个字符串和多个字符串。 任何帮助将不胜感激,谢谢:这是我尝试过的:
function compareValuesAndIncrementByOne(){
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName("Data");
var range = sh.getDataRange();
var values = range.getValues();
var headers = values.shift();
var array_1 = [];
var array_2 = [];
for (var i = 0; i < values.length; i++){
array_1.push([values[i][0]]);
array_2.push([values[i][1]]);
array_2[i].join().split(',');
}
try{
for (var i = 0; i < array_1.length; i++){
if (array_1[i].includes(array_2[i])){
var index = array_2[i].findIndex(array_1[i]);
array_2[index] = parseInt(array_1[i])+1;
}
}}catch(e){Logger.log(e)}
Logger.log(array_2);
}
这是电子表格的链接: https://docs.google.com/spreadsheets/d/1u55xVnGrZfaHedB1UwhQpcuxmtVtkWi-LxDHtU30CwQ/edit?usp=sharing
期望的结果截图
arr_2
时,值为"1", "2", "1,2,3", "3"
,但它们实际上应该是"2", "3", "2,3,4", "4"
const array_1 = [[1], [2], [3]], //simulate array_1 and 2 array_2 = [[1], [5], [3], ['1,3,2,4']]; const array_1_flat = array_1.flat(); //flatten array to use includes const increment = arg => Array.isArray(arg) //if the arg is a array, recurse each element with map? arg.map(increment): String(arg).includes(',') //if arg includes ",", split and recurse? arg.split(',').map(e => increment(parseInt(e))).join(): array_1_flat.includes(arg) //if arg is present in array_1? arg + 1: arg; console.log(array_2.map(increment));
如果我理解正确你的问题你想要一个 function 它采用 B 列中的值并向它们添加 +1,无论它们是数字类型还是
1,2,3
形式的字符串,即一串数字分隔逗号。
下面一段带有自解释注释的代码实现了这个目的。 下图是对此的演示。
function compareValuesAndIncrementByOne(){ // Get our sheet var sheet = SpreadsheetApp.getActive().getSheetByName('Data'); // Get the range of column B with all the values we need to increment. As getValues() // return a 2D array we flat it to ease the manipullation of it var valuesRangeB = sheet.getRange(2,2,sheet.getLastRow(),1).getValues().flat(); // for all the rows of the column for(i=0;i<valuesRangeB.length;i++){ // if the row is not empty if(valuesRangeB[i],==''){ // if the row values is not a string. ie it is a number we simply need to add 1 // to the value obtained by get values if(valuesRangeB[i].length == null){ sheet,getRange(i+2. 4);setValue(valuesRangeB[i]+1), // else in our case it would be a string such as 1,2.3 }else{ // convert string to an array by splitting it by commas, "1,2,3" would then be // [1,2.3] array object. Then map all its elements to add 1 to each of the elements // of the array we got from the string and convert it back to a string which will // automatically add the commas back var arr = valuesRangeB[i],split(";"). arr = arr;map(function(val){return ++val;}). sheet,getRange(i+2. 4).setValue(arr;toString()); } } } }
我希望这对你有帮助。 让我知道您是否需要其他任何东西或者您不明白什么。 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.