Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten 3D array containing objects to 2D removing duplicated objects by it's parameter

I have a 3D array with objects inside:

[
    [{ id: 1 }, { id: 2 }],
    [{ id: 3 }],
    [{ id: 3 }, { id: 4 }]
]

How to flatten it including removing duplicated id parameter?

[{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]

I think underscore would be helpful with that

like image 205
Szymon Toda Avatar asked Jun 18 '15 07:06

Szymon Toda


3 Answers

var a = [
    [{ id: 1 }, { id: 2 }],
    [{ id: 3 }],
    [{ id: 3 }, { id: 4 }]
];

var flattened = _(a).flatten().uniq('id').value();

Of course you have to include lodash to your webpage.

like image 143
itachi Avatar answered Nov 14 '22 22:11

itachi


You can use Underscore flatten and unique to accomplish this. However, whenever you are using multiple underscore operations, it is a good time to consider using the underscore chainging with chain and value:

var data = [
    [{ id: 1 }, { id: 2 }],
    [{ id: 3 }],
    [{ id: 3 }, { id: 4 }]
];

var result = _.chain(data)
                  .flatten()
                  .uniq(function(o) {
                      return o.id;
                   })
                  .value();

console.log('result', result);

JSFiddle: http://jsfiddle.net/0udLde0s/3/

Even shorter with current Underscore.js

If you use a recent version of Underscore.js (I tried current which is 1.8.3 right now), you can use .uniq('id') so it makes it even shorter:

var result = _.chain(data)
                  .flatten()
                  .uniq('id')
                  .value();
like image 22
Cymen Avatar answered Nov 14 '22 21:11

Cymen


You can use _.flatten, and _.uniq, like so

var data = [
    [{ id: 1 }, { id: 2 }],
    [{ id: 3 }],
    [{ id: 3 }, { id: 4 }]
];

var result = _.uniq(_.flatten(data), function (el) {
    return el.id;
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
like image 35
Oleksandr T. Avatar answered Nov 14 '22 23:11

Oleksandr T.