Search code examples
javascriptlodash

How to get intersection with lodash?


I am trying to return the matching ids in this array of objects:

const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
const arr2 =["1"]

How can I return just the id with value 1 in arr?


Solution

  • Lodash

    Probably the most concise working solution would be using the lodash _.intersectionBy but that would require your arr2 array to contain an object with an id:

    const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
    const arr2 =[{id:1}]  // <-- object with the `id`
    
    const result = _.intersectionBy(arr, arr2, 'id');
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

    Another way to do this with lodash would be via _.intersectionWith which does not require any changes on your given inputs:

    const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
    const arr2 =["1"]
    
    const result = _.intersectionWith(arr, arr2, (o,num) => o.id == num);
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

    The idea would be to provide it with a custom function to know how to compare the values between the 2 arrays.

    ES6 & Plain Javascript

    You can do this with JS only via Array.find if you are looking for just one item:

    const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
    const arr2 =["1"]
    
    const result = arr.find(x => arr2.some(y => x.id == y))
    console.log(result)

    You can use Array.filter in the case you have more ids in arr2:

    const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
    const arr2 =["1", "2"]
    
    const result = arr.filter(x => arr2.some(y => x.id == y))
    console.log(result)

    Since you have the ids in the arr you could also just use Array.map:

    const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
    const arr2 =["1"]
    
    const result = arr2.map(x => arr.find(y => y.id == x))
    console.log(result)

    Another option as mentioned by @ibrahim mahrir would be via Array.find & Array.includes:

    const arr = [{id:1,name:'Harry'},{id:2,name:'Bert'}]
    const arr2 =["1"]
    
    const result = arr.filter(x => arr2.includes(x.id.toString()))
    console.log(result)