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
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.
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();
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With