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

编程入门 行业动态 更新时间:2024-10-27 20:31:57
本文介绍了按属性值按特定顺序对数组对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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)

更多推荐

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

本文发布于:2023-11-30 00:56:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648191.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   顺序   属性   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!