按属性值按特定顺序对数组对象进行排序
我有一个对象数组,我想使用每个对象的属性值与相应值的有序列表进行比较.
I have an array of objects that I'd like to sort using each object's property value compared against an ordered list of corresponding values.
比方说,我有这个字符串数组;食物组:
Let's say I have this array of strings; food groups:
[ 'protein',
'dairy',
'fruit',
'vegetable' ]
我还有一系列对象,食物,每个对象都属于属性group
属于以前的食物组之一:
And I also have an array of objects, food items, each belonging to one of the former food groups by the property group
:
[
{ 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' },
]
给出第一个数组中食物组的顺序,如何使用食物的对象group
属性对食物进行排序,从而得出结果:
Given the order of the food groups in the first array, how can I sort the food items using their object group
properties, to result in this:
[
{ group: 'protein', name: 'beef' },
{ group: 'protein', name: 'tofu' },
{ group: 'protein', name: 'chicken' },
{ group: 'dairy', name: 'cheese' },
{ group: 'dairy', name: 'milk' },
{ group: 'fruit', name: 'apple' },
{ group: 'fruit', name: 'grapes' },
{ group: 'vegetable', name: 'broccoli' },
{ group: 'vegetable', name: 'peas' },
{ group: 'vegetable', name: 'bell pepper' },
]
虽然我使用Javascript进行编码,但是我确信这在几种语言中或多或少都是相同的.
While I'm doing this in Javascript, I'm sure this would be more or less the same across a few languages.
任何帮助将不胜感激!
您可以使用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)