【发布时间】:2021-05-20 14:06:24
【问题描述】:
假设我有一个数组和 2 个变量;一个是简单的字符串,一个是字符串值数组:
var street = "Fernwood Avenue";
var fips = ["34011", "34007"];
var test_array =[["06101123", "0", "0.2", "34011", "Cumberland", "Local", "Fernwood Avenue"],
["02271163", "0.1", "0.22", "34003", "Bergen", "Local", "Fernwood Avenue"],
["04351186", "0.3", "0.59", "34007", "Camden", "Local", "Fernwood Avenue"],
["07131150", "0", "0.3", "34013", "Essex", "Local", "Beacon Street"],
["03041026", "0", "0.13", "34005", "Burlington", "Local", "Beacon Street"],
["20121109", "0.18", "0.43", "34039", "Union", "Local", "Jones Lane"],
["15141139", "0", "0.27", "34029", "Ocean", "Local", "Jones Lane"]];
我在这里要做的是遍历我的 test_array 并在 sub_array[6] 中找到与 street 匹配的子数组,并且在 fips 列表中匹配 sub_array[3] (["34011", "34007" ])。有没有办法使用过滤器(或任何其他方法)来实现这一点并返回以下结果?
var new_array = [["06101123", "0", "0.2", "34011", "Cumberland", "Local", "Fernwood Avenue"],
["04351186", "0.3", "0.59", "34007", "Camden", "Local", "Fernwood Avenue"]];
*奖励:假设有一个函数,其中街道和 fips 作为列表参数进入,其中街道名称将始终存在,但 fips 值可能会或可能不会。所以,
var keyword = ["Fernwood Avenue", "34011", "34007"];
或
var keyword = ["Fernwood Avenue"];
或
var keyword = ["Fernwood Avenue", "34011"];
使用类似这样的函数(*这不适用于场景 1)
function matcher(array1, array2) {
return array1.every(value => array2.includes(value));
}
function array_parser(array, keywords) {
return array.filter(values => matcher(keywords, values));
}
var new_array = array_parser(test_array, keywords);
【问题讨论】:
标签: javascript arrays parsing filter