3

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

0

2 Answers 2

2

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>

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

Comments

2

Here's an answer using VanillaJS

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


const needToFind = [4, 1];

const results = roles.filter(obj => needToFind.includes(obj.value))

console.log(results)

Basically you apply filter on roles and using includes to see if value exist in needtoFind

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.