Reputation: 183
I need to reduce this array of objects
[
{id:1, value:'A'},
{id:2, value:'B'},
{id:3, value:'B'},
{id:4, value:'B'},
{id:5, value:'A'},
{id:6, value:'A'},
{id:7, value:'B'}
]
to
[
{id:1, value:'A'},
{id:2, value:'B'},
{id:5, value:'A'},
{id:7, value:'B'}
]
If consecutive objects have the same value, it keeps the first one and removes the rest.
My current solution is
var lastValue = undefined;
var result = [];
var propPath = 'value'; // I need later to reference nested props
objects.filter(function(object){
var value = _.at(object, propPath);
if (!_.isEqual(value, lastValue)){
result.push(object);
lastValue = value;
}
});
console.log(result);
My questions is, as Lodash has a lot of features, is there a Lodash way of doing this more simply? Maybe some pre-built solution without using helper variables (lastValue and result).
Upvotes: 4
Views: 2261