我有以下两个数组:
const raceOptions = [
{
"label": "race_option_american_indian_alaska_native",
"value": "American Indian/Alaska Native"
},
{
"label": "race_option_asian",
"value": "Asian"
},
{
"label": "race_option_black_african_american",
"value": "Black/African American"
},
{
"label": "race_option_native_hawaiian_pacific_islander",
"value": "Native Hawaiian or Other Pacific Islander"
},
{
"label": "race_option_white",
"value": "White"
},
{
"label": "prefer_not_to_say",
"value": ""
}
]
const selectedRace = [
"American Indian/Alaska Native",
"Native Hawaiian or Other Pacific Islander",
"Black/African American"
]
如何合并/过滤这些数组以输出一个新数组,如下所示?
const filteredArray = [
'race_option_american_indian_alaska_native',
'race_option_native_hawaiian_pacific_islander',
'race_option_black_african_american'
]
1条答案
按热度按时间nkkqxpd91#
使用Array对象的
.forEach()
方法,可以迭代raceOptions
数组中的元素。在它的回调函数中,您需要将当前元素的.value
属性与第二个数组selectedRace
中的所有元素进行比较。这可以通过数组的
.find()
方法来完成,该方法将根据搜索查询返回元素的。过滤后的元素最终需要被推入新数组filteredArray
。