-2

I've been trying to group elements with the same values in the array for hours but I'm going nowhere

Array:

list = [
    {id: "0", created_at: "foo1", value: "35"},
    {id: "1", created_at: "foo1", value: "26"},
    {id: "2", created_at: "foo", value: "13"},
    {id: "3", created_at: "foo1", value: "11"},
    {id: "4", created_at: "foo", value: "11"},
    {id: "5", created_at: "foo1", value: "16"},
    {id: "6", created_at: "foo", value: "26"},
    {id: "7", created_at: "foo1", value: "13"},
    {id: "8", created_at: "foo1", value: "16"}
];

The result I'm trying to get is:

var result = [
    [
        {id: "0", created_at: "foo1", value: "35"}
    ],
    [
        {id: "1", created_at: "foo1", value: "26"},
        {id: "6", created_at: "foo", value: "26"}
    ],
    [
        {id: "2", created_at: "foo", value: "13"},
        {id: "7", created_at: "foo1", value: "13"}
    ],
    [
        {id: "3", created_at: "foo1", value: "11"},
        {id: "4", created_at: "foo", value: "11"}
    ],
    [
        {id: "5", created_at: "foo1", value: "16"},
        {id: "8", created_at: "foo1", value: "16"}
    ]         
];

any ideas how to get that? thanks in advance.

Note: I'm working with angular 5.

Rildo Gomez
  • 305
  • 8
  • 21

1 Answers1

1

If you're considering using Lodash for this, you could use _.groupBy for this:

var list = [
    {id: "0", created_at: "foo1", value: "35"},
    {id: "1", created_at: "foo1", value: "26"},
    {id: "2", created_at: "foo", value: "13"},
    {id: "3", created_at: "foo1", value: "11"},
    {id: "4", created_at: "foo", value: "11"},
    {id: "5", created_at: "foo1", value: "16"},
    {id: "6", created_at: "foo", value: "26"},
    {id: "7", created_at: "foo1", value: "13"},
    {id: "8", created_at: "foo1", value: "16"}
];

var response = _.groupBy(list, 'value');

console.log(response);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
SiddAjmera
  • 38,129
  • 5
  • 72
  • 110