0

I have 2 arrays of objects with ids:

    const oldOffers = [
  {
    _id: "1"
  },
  {
    _id: "2"
  },
  {
    _id: "3"
  }
];

const activeOffers = [
  {
    _id: "1"
  },
  {
    _id: "5"
  }
];

I need to have a new array with objects that are present in oldOffers but are not present in activeOffers; so output will be:

filteredOffers = [{
        _id: "2"
      },
      {
        _id: "3"
      }
    ];

I solved this problem using 2 loops but in bad way, have someone any elegant solution, also that uses lodash?

4 Answers4

5

Why would you need a library for that at all? It's doable with .filter and .find in one line :)

const oldOffers = [
  {_id: "1"},
  {_id: "2"},
  {_id: "3"}
];

const activeOffers = [
  {_id: "1"},
  {_id: "5"}
];

const filtered = oldOffers.filter( obj1 => !activeOffers.find(obj2 => obj1._id===obj2._id));

console.log(filtered)
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • You could have store the `activeOffers`'s `_id` in a [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) and then use `has` method of set to achieve the same result in more efficient way. – DecPK Aug 31 '21 at 10:11
  • And there's no other [question](https://stackoverflow.com/questions/21987909/how-to-get-the-difference-between-two-arrays-of-objects-in-javascript) that would answer this and therefor be a valid dupe? – Andreas Aug 31 '21 at 10:11
  • It seems like `Nina` has already answered what I was saying. – DecPK Aug 31 '21 at 10:12
  • 1
    @Andreas I know, but basically every question is a duplicate nowadays. How are we supposed to glean some rep? :) – Jeremy Thille Aug 31 '21 at 10:25
2

You can solve this using the lodash differenceBy method

  const oldOffers = [
  {
    _id: "1"
  },
  {
    _id: "2"
  },
  {
    _id: "3"
  }
];

const activeOffers = [
  {
    _id: "1"
  },
  {
    _id: "5"
  }
];
_.differenceBy(oldOffers, activeOffers, '_id');
olayemii
  • 590
  • 1
  • 3
  • 16
2

You could create a set of _id and filter the other array.

const
    oldOffers = [{ _id: "1" }, { _id: "2" }, {  _id: "3" }],
    activeOffers = [{ _id: "1" }, { _id: "5" }],
    active = new Set(activeOffers.map(({ _id }) => _id));
    filtered = oldOffers.filter(({ _id }) => !active.has(_id));

console.log(filtered);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Or... [How to get the difference between two arrays of objects in JavaScript](https://stackoverflow.com/questions/21987909/how-to-get-the-difference-between-two-arrays-of-objects-in-javascript) – Andreas Aug 31 '21 at 10:12
0
var result = {};
var keys = Object.keys(activeOffers);

for (var key in oldOffers)
    {
    if (!keys.includes(key)) 
        {
            result[key] = oldOffers[key];
        }
    }
}

Also doable with Object.keys and includes in a single for loop. The above filtered oneliner looks really nice though.

DragonInTraining
  • 385
  • 1
  • 12