mr.Kame
mr.Kame

Reputation: 183

Lodash: Remove consecutive duplicates from an array

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

Answers (1)

GG.
GG.

Reputation: 21854

This can be solved with .reject:

_.reject(objects, function (object, i) {
    return i > 0 && objects[i - 1].value === object.value;
});

DEMO

Upvotes: 4

Related Questions