0

Using lodah - how to remove the object by it's value?

here is my try:

var array = ['Education', 'Medicine'];

values = [
    {
      "Category":"Medicine"
    },

    {
      "Category":"Medicine"
    },
    {
      "Category":"Development"
    },
    {
      "Category":"Education"
    }
  ]

  const x = _.without(values, array);

console.log(x); expected value is :

values = [{
  "Category":"Development"
},]

2 Answers 2

1

You can use _.differenceWith() to remove items with a Category that exists in the array.

const array = ['Education', 'Medicine'];

const values = [{"Category":"Medicine"},{"Category":"Medicine"},{"Category":"Development"},{"Category":"Education"}];

const result = _.differenceWith(values, array, (o, category) => o.Category === category);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

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

4 Comments

- how to get the values as included only, opposite of current function? I tried o.Category !== category - but not works
Use intersectionWith instead of differenceWith.
intersectionWith - is not taking array of values at present it takes one last value as Medicine
Interesting, it seems like a glitch in intersectionWith. The number of results is limited by the 2nd array. In that case you can use @cocoder's answer with !array.includes().
1

Actually, I don't think use lodash is better. You can use es6 to solve it.

result = values.filter(x => array.includes(x.Category));

Comments

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.