4

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

0

1 Answer 1

4

This can be solved with .reject:

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

DEMO

Sign up to request clarification or add additional context in comments.

2 Comments

This is exactly what I need, but the lodash documentation says nothing about the second argument (index) of the predicate. Is the document outdated or is this something unofficial, internal, or subject to change?
All the methods to manipulate collections have a predicate with three arguments: (value, index|key, collection). I guess it's just missing in _.reject documentation but the other ones have this detail (_.filter, _.map, _.forEach, _.every, _.some, etc). For info, the third argument collection is useful in some case, e.g. _.filter(_.sortBy(items, 'id'), function (item, i, sortedItems) { … }.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.