按属性值按特定顺序对数组对象进行排序 [英] Sort array objects by property value in specific order

查看:233
本文介绍了按属性值按特定顺序对数组对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,我想使用每个对象的属性值与相应值的有序列表进行比较.

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)

这篇关于按属性值按特定顺序对数组对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆