简体   繁体   中英

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).

This can be solved with .reject :

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

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM