Как увеличить каждый строковый элемент из одного массива, который находится в другом массиве? - PullRequest
1 голос
/ 04 августа 2020

Я как бы застрял в этой проблеме, цель состоит в том, чтобы найти совпадающие значения из столбца A в столбце B и увеличить те же значения на 1 только в столбце B, это касается как одиночных, так и многих символьных строк. Любая помощь будет принята с благодарностью, спасибо! Вот что я пробовал:

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"

Ответы [ 2 ]

1 голос
/ 04 августа 2020

Используйте Array.map с рекурсией :

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));
0 голосов
/ 04 августа 2020

Решение

Если я правильно понял ваш вопрос, вам нужна функция, которая принимает значения в столбце 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, i.e 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());
        
      }
    }
  }
}

введите описание изображения здесь

Надеюсь, это вам помогло. Дайте мне знать, если вам еще что-нибудь понадобится или вы чего-то не поняли. :)

...