按关键字按数组分组 [英] Group by element in array by keyword

查看:96
本文介绍了按关键字按数组分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在AngularJS(1)上开发一个应用程序,但我不知道如何按项目拆分另一个数组组中的项目数组.

I am developing an application on AngularJS (1) and I can not figure out how to split array of items in another array group by item.

我的意思是我有一系列不同的项目,我会按uuid将项目分组,例如:

I mean I have an array of different items and I would group items by uuid like:

[
    {"name": "toto", "uuid": 1111},
    {"name": "tata", "uuid": 2222},
    {"name": "titi", "uuid": 1111}
];

将会是:

[
    [
        {"name": "toto", "uuid": 1111},
        {"name": "titi", "uuid": 1111}
    ],
    [
        {"name": "tata", "uuid": 2222}
    ]
];

我已经尝试过遍历forEach函数,但是如果我的数组很长很长

I have tried loop and loop again on forEach function but it's very long if my array is long

推荐答案

您可以使用哈希表并将对象收集在哈希表的数组中.

You could use a hash table and collect the object in the arrays of the hash table.

var array = [{ name: "toto", uuid: 1111 }, { name: "tata", uuid: 2222 }, { name: "titi", uuid: 1111 }],
    hash = Object.create(null),
    result = [];

array.forEach(function (a) {
    if (!hash[a.uuid]) {
        hash[a.uuid] = [];
        result.push(hash[a.uuid]);
    }
    hash[a.uuid].push(a);
});

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于按关键字按数组分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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