google-apps-script - Google Scripts Concatenate Cells in different columns
问题描述
I have the following scenario where I want to concatenate cells in different columns but the quantity of columns differs from case to case.
example1: In cell A2 there is the value of 70286 & and the cell B2 there is the value of playmobil. The end result in F2 should be +70286 +playmobil
example2: In cell A4 there is the value of 70666, in the cell B4 there is the value of lego and in the cell C4 there is the value of ninjago. The end result in F2 should be +70666 +lego +ninjago
解决方案
Solutions:
Google Sheet Formula:
You can use TEXTJOIN and if you want a plus sign in front of the string you can use CONCAT to add it.
Use this formula in column F:
=CONCAT("+",textjoin(" +", 1, A2:E2))
If you don't know how many columns you want to use, then you can select the full row:
=CONCAT("+",textjoin(" +", 1, A2:2))
Google Apps Script:
- We get the data of the second row as a 2D array using getValues().
- Then we apply flat() to convert it to 1D.
- The next step is to remove the empty cells by using filter().
- Finally, we use reduce() to get the final string as the sum of all strings.
The logic can be easily adjusted. You can do this logic for multiple cells etc.
Code snippet:
function myFunction() {
const sh = SpreadsheetApp.getActive().getSheetByName('Sheet1');
const row = 2;
const data=sh.getRange(row,1,1,sh.getMaxColumns()).
getValues().
flat().
filter(c=>c!='').
reduce( (a, b) => `${a} +${b}`);
const result = `+${data}`;
sh.getRange('F1').setValue(result);
Logger.log(result);
}
推荐阅读
- python-3.x - Python 搜索功能
- node.js - 当从浏览器调用 API 时,自定义请求标头被删除
- node.js - 如何将时间戳数据类型从 Firestore 复制到 Cloud SQL Postgres?
- node.js - 使用 mongoose 和 node express 查找一个集合中的所有文档,更改数据并保存到另一个集合中
- javascript - 传单从地图单击创建标记并访问拖动事件的结束
- javascript - 在嵌套对象中查找任何错误值的更好的 vanilla JS 方法?
- r - 通过添加 0 和 1 的新列,为 R 中列中的值或因子的第一个实例返回 1,为所有其他后续实例返回 0
- typescript - 如何在我的 Typescript Vue 组件中启用 chrome 类型的自动完成功能?
- woocommerce - Woocommerce:将“字段描述”移动到“标签”下方的挂钩?
- scalardl - Bastion 服务器的全局 IP 地址更改后,我需要做什么吗?