Basically, that's not the way you check if a value exists in an array. Within the context of Google Apps Script, you should use indexOf()
(see here for which array methods are supported).
When you compare e[2] == arr2
, you're actually checking if ["Solar"] == ["Solar","Wind"]
. Clearly, it's not the same. So you need to check if e[2][0]
, which is just "Solar", exists in the filter array. Using arr2.indexOf(e[2][0])
will return the index of where "Solar" exists in the array; if the value doesn't exist, it will return -1
. So all you need to do is check for that -1
.
If you can assume that the filter values will always be in the third position, then you can use this fairly simple implementation.
var arr1 = [
[["John"],[50],["Solar"],["Egypt"]],
[["Joe"],[60],["Wind"],["Ghana"]],
[["Alan"],[70],["Coal"],["Nigeria"]]
];
var arr2 = ["Solar","Wind"];
var result = arr1.filter(function(e) {
return arr2.indexOf(e[2][0]) != -1;
});
Logger.log(result);
Otherwise, you need to check all of the elements of the array. This approach assumes that all of the values are wrapped in their own array, so it extracts them into a single array using map()
. You can then use some()
to check against all of the filter values.
var arr1 = [
[["John"],[50],["Solar"],["Egypt"]],
[["Joe"],[60],["Wind"],["Ghana"]],
[["Alan"],[70],["Coal"],["Nigeria"]]
];
var arr2 = ["Solar","Wind"];
var result = arr1.filter(function(e) {
var joined = e.map(function(element) { return element[0] });
return arr2.some(function(filterVal) { return joined.indexOf(filterVal) != -1});
});
Logger.log(result);