更新时间:2023-01-30 12:51:47
您可以使用forEach
& filter
数组方法.遍历food groups
&对于每个元素,请从group
中过滤出匹配的元素,&存储在新数组中
You can use forEach
& filter
array method. Iterate over the food groups
& for each element filter out the matched element from the group
, & store in a new array
var order = ['protein',
'dairy',
'fruit',
'vegetable'
]
var orgArry = [{
group: 'vegetable',
name: 'broccoli'
},
{
group: 'protein',
name: 'beef'
},
{
group: 'fruit',
name: 'apple'
},
{
group: 'vegetable',
name: 'peas'
},
{
group: 'dairy',
name: 'cheese'
},
{
group: 'protein',
name: 'tofu'
},
{
group: 'vegetable',
name: 'bell pepper'
},
{
group: 'dairy',
name: 'milk'
},
{
group: 'fruit',
name: 'grapes'
},
{
group: 'protein',
name: 'chicken'
},
];
var newArray = [];
order.forEach(function(item) {
return orgArry.filter(function(groupName) {
if (groupName.group === item) {
newArray.push(groupName)
}
})
});
console.log(newArray)