在应用脚本中,我具有以下内容:
function diff(A, B) {
return A.filter(function (a) {
return B.indexOf(a) == -1;
});
}
当我跑步时:
function testArray(){
ta = ['a','b','c','d']
ts = ['a','b','c']
o =diff(ta,ts)
Logger.log(o);
}
我得到:['d']-正确的答案,现在我正在尝试将过滤器应用于二维值数组-Google工作表。
我尝试过:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var target_sheet_range = ss.getSheets()[1].getDataRange();
var target_sheet_values = target_sheet_range.getValues();
Logger.log('target_sheet_values');
Logger.log(target_sheet_values);
var range = ss.getSheets()[0].getDataRange();
var values = range.getValues();
Logger.log('values');
Logger.log(values);
var diff_values = diff(values, target_sheet_values)
,但这没有考虑数组的2d性质。您可以在Google电子表格https://docs.google.com/spreadsheets/d/1fFr9Sz2EAiMYoybg-evV33n_BZjF-1QNnnKqiqSXQ_g/edit?usp=sharing
上看到它输出:
[18-06-23 14:45:22:129 EDT] target_sheet_values
[18-06-23 14:45:22:130 EDT] [[a, a, a, a, a], [z, x, c, v, b], [m, n, b, v, c]]
[18-06-23 14:45:22:457 EDT] values
[18-06-23 14:45:22:458 EDT] [[a, a, a, a, a], [z, x, c, v, b], [m, n, b, v, c], [a, s, d, f, g], [q, w, e, r, t]]
[18-06-23 14:45:22:459 EDT] hhhhhh
[18-06-23 14:45:22:459 EDT] [[a, a, a, a, a], [z, x, c, v, b], [m, n, b, v, c], [a, s, d, f, g], [q, w, e, r, t]]
如何修改过滤器功能2过滤2d数组
答案 0 :(得分:2)
您的问题与javascript document.getElementById('htmlbutton').click();
中的事实有关。值不完成数组和对象的比较。这也适用于[1, 2, 3] != [1, 2, 3]
。例如:
indexOf()
要解决此问题,您需要编写一个函数,该函数以所需的方式定义相等性。例如:
var a = [[1, 2, 3], [4, 5, 6]]
var b = [4, 5, 6]
console.log(a.indexOf(b)) // returns -1
有了这个,您现在可以使用以下内容进行过滤:
// arrays with the same values in the same order will be considered equal
function array_equals(a, b){
return a.length === b.length && a.every((item,idx) => item === b[idx])
}
console.log(array_equals([1, 2, 3], [1, 2, 3]))
console.log(array_equals([1, 2, 3], [1, 2, 4]))
答案 1 :(得分:1)
您要从text-align: center;
和[[a, s, d, f, g], [q, w, e, r, t]]
中检索[[a, a, a, a, a], [z, x, c, v, b], [m, n, b, v, c], [a, s, d, f, g], [q, w, e, r, t]]
。如果我的理解是正确的,那么该示例脚本如何?我认为您的情况有几个答案。请认为这是其中之一。
[[a, a, a, a, a], [z, x, c, v, b], [m, n, b, v, c]]
var res = values.filter(
function(e) {
return target_sheet_values.filter(
function(f) {
return e.toString() == f.toString()
}).length == 0
});
var target_sheet_values = [
["a","a","a","a","a"],
["z","x","c","v","b"],
["m","n","b","v","c"]
];
var values = [
["a","a","a","a","a"],
["z","x","c","v","b"],
["m","n","b","v","c"],
["a","s","d","f","g"],
["q","w","e","r","t"]
];
var res = values.filter(
function(e) {
return target_sheet_values.filter(
function(f) {
return e.toString() == f.toString()
}).length == 0
});
console.log(res);
[["a","s","d","f","g"],["q","w","e","r","t"]]
和values
来自您的脚本。target_sheet_values
。如果我误解了您想要什么,请告诉我。我想修改它。