Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash find array in array

Tags:

lodash

I have an array that looks like this:

   var roles = [ 
           { "label": "Super Auditor", "value": 4 }, 
           { "label": "Super Finance Officer", "value": 3 }, 
           { "label": "Super Manager", "value": 2 }, 
           { "label": "Super Admin", "value": 1 } 
   ]

I need to find if it is in array and get that object.

var needToFind = [4, 1]

Expected Results:

var results =[
              { "label": "Super Auditor", "value": 4 }, 
              { "label": "Super Admin", "value": 1 } 
            ]

I just don't know how to do it. TY

like image 469
Rbex Avatar asked Jul 25 '26 13:07

Rbex


1 Answers

You can use _.intersectionWith():

var roles = [ 
  { "label": "Super Auditor", "value": 4 }, 
  { "label": "Super Finance Officer", "value": 3 }, 
  { "label": "Super Manager", "value": 2 }, 
  { "label": "Super Admin", "value": 1 }
]

var needToFind = [4, 1]

var result = _.intersectionWith(roles, needToFind, (a, b) => a.value === b)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
like image 193
Ori Drori Avatar answered Jul 28 '26 06:07

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!