我需要一些帮助,我必须按区域和年份的元素过滤arr对象,我尝试使用filter方法,但是由于事先的原因,我不知道该如何实现。
let arr = [
{ id: 1, region: ["china"], year: ["1990"] },
{ id: 2, region: ["china"], year: ["2010"] },
{ id: 3, region: ["taiwan"], year: ["1990"] },
{ id: 4, region: ["corea"], year: ["1990"] },
{ id: 5, region: ["corea"], year: ["2010"] },
];
let regions = ["china", "taiwan"];
let years = ["1990"];
let expectedOutput = [{ id: 1, region: ["china"], year: ["1990"] },
{ id: 2, region: ["china"], year: ["2010"] },
{ id: 3, region: ["taiwan"], year: ["1990"] },
{ id: 4, region: ["corea"], year: ["1990"] }];
答案 0 :(得分:1)
过滤
let arr = [
{ id: 1, region: ["china"], year: ["1990"] },
{ id: 2, region: ["china"], year: ["2010"] },
{ id: 3, region: ["taiwan"], year: ["1990"] },
{ id: 4, region: ["corea"], year: ["1990"] },
{ id: 5, region: ["corea"], year: ["2010"] },
];
let regions = ["china", "taiwan"];
let years = ["1990"];
let result = arr.filter(({region, year}) => region.some(el => regions.includes(el)) || year.some(year => years.includes(year)));
console.log(result);
答案 1 :(得分:1)
您可以采用对象键的条目作为具有所需键和可能值的过滤器,而不是采用硬连线的方法。
import pandas as pd
import numpy as np
from sklearn.naive_bayes import MultinomialNB
from sklearn.multioutput import MultiOutputClassifier
df_train = pd.DataFrame({'feature': [1, 2, 3, 3, 4, 4, 5]})
df_train_labels = pd.DataFrame({'class1': ['1-3', '1-3','1-3', '1-3', '4-5', '4-5', '4-5'], 'class2': ['1-2', '1-2', '3-5', '3-5', '3-5', '3-5', '3-5']})
prediction_model = MultiOutputClassifier(MultinomialNB())
prediction_model.fit(df_train, df_train_labels) # Works fine
prediction_model.partial_fit(df_train,\
df_train_labels,\
np.unique(df_train_labels)) # Error
答案 2 :(得分:1)
请尝试
let arr = [
{ id: 1, region: ["china"], year: ["1990"] },
{ id: 2, region: ["china"], year: ["2010"] },
{ id: 3, region: ["taiwan"], year: ["1990"] },
{ id: 4, region: ["corea"], year: ["1990"] },
{ id: 5, region: ["corea"], year: ["2010"] }
];
let regions = ["china", "taiwan"];
let years = ["1990"];
let result = arr.filter((row) => {
if (regions.includes(row.region[0]) ) {
return row;
} else if (years.includes(row.year[0])) {
return row;
}
});
console.log(result.length);
for (row of result) {
console.log(row);
}
输出:
4
{ id: 1, region: [ 'china' ], year: [ '1990' ] }
{ id: 2, region: [ 'china' ], year: [ '2010' ] }
{ id: 3, region: [ 'taiwan' ], year: [ '1990' ] }
{ id: 4, region: [ 'corea' ], year: [ '1990' ] }
答案 3 :(得分:0)
let arr = [
{ id: 1, region: ["china"], year: ["1990"] },
{ id: 2, region: ["china"], year: ["2010"] },
{ id: 3, region: ["taiwan"], year: ["1990"] },
{ id: 4, region: ["corea"], year: ["1990"] },
{ id: 5, region: ["corea"], year: ["2010"] },
];
let regions = ["china", "taiwan"];
let years = ["1990"];
arr=arr.filter(obj => regions.includes(obj.region[0]) || years.includes(obj.year[0]));
console.log(arr);