如何对具有相同属性

时间:2018-05-17 17:12:58

标签: javascript node.js

我有一个数组,如下所示。数组中的每个元素都是一个包含多个属性的对象。调用其中一个属性 “priorityTag”。根据代码belwo,我根据每个对象中的priorityTag对数组进行排序。代码工作正常。

某些对象包含相同的priorityTag。我想要做的是,将包含相同priorityTag的类似对象组合在一起。

例如,如果数组包含以下内容:

示例

arr[{prop1: "aaa1", prop2:"yas1", priorityTag:100},//group1
{prop1: "aaa2", prop2:"yas2", priorityTag:200},//group2
{prop1: "aaa3", prop2:"yas3", priorityTag:100},//group1
{prop1: "aaa4", prop2:"yas4", priorityTag:200},//group2
{prop1: "aaa5", prop2:"yas5", priorityTag:300},//group3
{prop1: "aaa6", prop2:"yas6", priorityTag:400},//group4
{prop1: "aaa7", prop2:"yas7", priorityTag:300},//group3
{prop1: "aaa8", prop2:"yas8", priorityTag:400},//group4
{prop1: "aaa9", prop2:"yas9", priorityTag:500},//group5
{prop1: "aaa10", prop2:"yas10", priorityTag:700},//group6
{prop1: "aaa11", prop2:"yas11", priorityTag:700},//group6
]

我想得到一个包含具有相同priorityTag的对象组的数组。

我想拥有Array of Arrays.each元素在主Array中是Array包含具有相同priorityTag的对象

请让我知道如何正确地做到这一点

sortFeaturesPerPriority2(arr) {
    logger.debug('[sortFeaturesPerPriority2]: Array.isArray(arr):', Array.isArray(arr));
    logger.debug('[sortFeaturesPerPriority2]: arr:', arr);
    logger.debug('[sortFeaturesPerPriority2]: arr.length:', arr.length);

    arr.sort((a, b) => a.getPriorityTag() - b.getPriorityTag());
    logger.debug('[sortFeaturesPerPriority2]: arr.sort:', arr);

    return arr;
  }

2 个答案:

答案 0 :(得分:1)

这是一种方法。您可以按键将项目分组到对象中,然后如果需要数组数组,只需将键映射到数组数组中,如下所示:



arr = [{prop1: "aaa1", prop2:"yas1", priorityTag:100},//group1
{prop1: "aaa2", prop2:"yas2", priorityTag:200},//group2
{prop1: "aaa3", prop2:"yas3", priorityTag:100},//group1
{prop1: "aaa4", prop2:"yas4", priorityTag:200},//group2
{prop1: "aaa5", prop2:"yas5", priorityTag:300},//group3
{prop1: "aaa6", prop2:"yas6", priorityTag:400},//group4
{prop1: "aaa7", prop2:"yas7", priorityTag:300},//group3
{prop1: "aaa8", prop2:"yas8", priorityTag:400},//group4
{prop1: "aaa9", prop2:"yas9", priorityTag:500},//group5
{prop1: "aaa10", prop2:"yas10", priorityTag:700},//group6
{prop1: "aaa11", prop2:"yas11", priorityTag:700},//group6
];

// arrays grouped in object by key
var grouped = arr.reduce((result, curr) => {
  // if key doesn't exist yet on obj, create it and initialize to empty array
  result[curr.priorityTag] = result[curr.priorityTag] || [];
  // push the current element to the proper group
  result[curr.priorityTag].push(curr);
  return result;
}, {});
//console.log(grouped);

// map object key/values into array of arrays
var groupedArrs = Object.values(grouped);

console.log(groupedArrs);




答案 1 :(得分:0)

这是一个非常简单的解决方案

result = []
arr.forEach( (element) => { 
    if(result[element.priorityTag] == undefined)
    { 
        result[element.priorityTag] = []; 
    } 
    result[element.priorityTag].push( element ) 
});

结果将是一个数组。如果您更喜欢某个对象,只需将result = []替换为result = {}

即可