且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按属性值按特定顺序对数组对象进行排序

更新时间: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)