过滤其中包含另一个数组的数组

时间:2019-12-23 16:27:18

标签: javascript arrays filter

我正在尝试过滤数组

const array = [{
    city: "Fullerton",
    routes: ["Route 1", "Route 2"],
    state: "CA"
}, {
    city: "Long Beach",
    routes: ["Route 3", "Route 4"],
    state: "CA"
}, {
    city: "Huntington Beach",
    routes: "Route 1",
    state: "CA"
}];

通过另一个数组:

const routes = ["Route 1", "Route 3"];

但是,我在过滤原始数组的路由项时遇到了麻烦,因为它具有数组和字符串作为其变量。不管变量类型如何,有没有办法使用路由数组并过滤原始数组?

此外,我希望这样做,以便如果您选择一条路由,即使数组元素包含更多路由,它也将过滤数组。

3 个答案:

答案 0 :(得分:1)

如果您希望至少有一条路线匹配,则可以组合someincludes

const routes = ["Route 1", "Route 3"];
const array = [{city: "Fullerton", routes: ["Route 1", "Route 2"], state: "CA"}, {city: "Long Beach", routes: ["Route 3", "Route 4"], state: "CA"}, {city: "Huntington Beach", routes: "Route 1", state: "CA"}];

const filteredArray = array.filter(a =>
  [].concat(a.routes).some(r => routes.includes(r))
)

console.log(filteredArray)

如果您需要完全匹配的所有路由,那么includes就足够了:

const routes = ["Route 1", "Route 3"];
const array = [{city: "Fullerton", routes: ["Route 1", "Route 2"], state: "CA"}, {city: "Long Beach", routes: ["Route 3", "Route 4"], state: "CA"}, {city: "Huntington Beach", routes: "Route 1", state: "CA"}];

const filteredArray = array.filter(a => routes.includes(a.routes))

console.log(filteredArray)

答案 1 :(得分:1)

您可以将字符串转换为数组,并检查其中的某些项目是否位于routes中。

var array = [{ city: "Fullerton", routes: ["Route 1", "Route 2"], state: "CA" }, { city: "Long Beach", routes: ["Route 3", "Route 4"], state: "CA" }, { city: "Huntington Beach", routes: "Route 1", state: "CA" }],
    routes = ["Route 1", "Route 3"],
    result = array.filter(o => [].concat(o.routes).some(s => routes.includes(s)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

如果filter中的every元素对应于routes的某个元素,则可以routes数组:

const result = array.filter(f=> 
    Array.isArray(f.routes) ? f.routes.every(r => routes.includes(r)) : false);

一个例子:

const array = [{
    city: "Fullerton",
    routes: ["Route 1", "Route 2"],
    state: "CA"
}, {
    city: "Long Beach",
    routes: ["Route 3", "Route 4"],
    state: "CA"
}, {
    city: "Huntington Beach",
    routes: "Route 1",
    state: "CA"
}, {
    city: "Huntington Beach 1",
    routes: ["Route 1", "Route 3"],
    state: "CA"
}
];

const routes = ["Route 1", "Route 3"];

const result = array.filter(f=> 
    Array.isArray(f.routes) ? f.routes.every(r => routes.includes(r)) : false);

console.log(result);