How to get intersection with lodash?

后端 未结 1 1660
自闭症患者
自闭症患者 2021-02-07 18:49

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\"]

H

1条回答
  •  执笔经年
    2021-02-07 19:01

    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)

    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)

    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)

    0 讨论(0)
提交回复
热议问题