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?

1
  • What was the code for your solution and why do you think it's bad? Commented Aug 31, 2021 at 9:58

4 Answers 4

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)

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

4 Comments

You could have store the activeOffers's _id in a Set and then use has method of set to achieve the same result in more efficient way.
And there's no other question that would answer this and therefor be a valid dupe?
It seems like Nina has already answered what I was saying.
@Andreas I know, but basically every question is a duplicate nowadays. How are we supposed to glean some rep? :)
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');

Comments

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

1 Comment

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.