0

I am trying to filter data which are present in an array using lodash. I am trying to filter like SQL IN clause.

ex: - select * from Test where id IN (2,4,5,67); 

JSON:

storedData = [
    {
        "id" : 1,
        "name" : "ABC"
    },
    {
        "id" : 2,
        "name" : "XYZ"
    },
    {
        "id" : 3,
        "name" : "BVX"
    },
    {
        "id" : 4,
        "name" : "OOO"
    }
]

Search criteria:

[2,4,5,67]

Required Output:

output = [
    {
        "id" : 2,
        "name" : "XYZ"
    },
    {
        "id" : 4,
        "name" : "OOO"
    }
]

Below is my code which i tried to implement

output = _.filter(storedData, (value) => {
    return value.id == 2 || value.id == 4 || value.id == 5 || value.id == 67
});

Could you please help me how to filter like IN clause ?

2 Answers 2

3

You can find the intersection between the two arrays using intersectionWith, which allows you to provide a callback and will keep all elements from the first array which the callback returns true for.

See example below:

const storedData = [ { "id" : 1, "name" : "ABC" }, { "id" : 2, "name" : "XYZ" }, { "id" : 3, "name" : "BVX" }, { "id" : 4, "name" : "OOO" } ];
const search = [2,4,5,67];

const res = _.intersectionWith(storedData, search, (o, n) => o.id === n); 
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

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

Comments

2

Use .includes

_.filter(storedData, (value) => _.includes(criteria, value.id))

const storedData = [
  {
    id: 1,
    name: "ABC",
  },
  {
    id: 2,
    name: "XYZ",
  },
  {
    id: 3,
    name: "BVX",
  },
  {
    id: 4,
    name: "OOO",
  },
]

const criteria = [2, 4, 5, 67]

const output = _.filter(storedData, (value) => _.includes(criteria, value.id))

console.log(output)
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

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.