0

I have two arrays . One with array of objects and other plain array.

Need to search the first array from all the levels of first array.

let arr1 = [{"LEVEL":1},{"LEVEL":2},{"LEVEL":3,"POSITION":"FCONTROLLER"}, 
            {"LEVEL":4,"POSITION":"RGM"},{"LEVEL":5,"POSITION":"GM"},{"LEVEL":5,"POSITION":"GMH"},{"LEVEL":6},{"LEVEL":7,"POSITION":"EGM"}]

let arr2 = [1,3,5]

Output :

 ["FCONTROLLER","GM","GMH"]

I tried to use reduce method but gives empty result.

  arr2.reduce((a, o) => (o.merged==='1'||o.merged==='3'||o.merged==='5' && a.push(o.value), a), [])

2 Answers 2

1

You can use indexOf to search for the index of the element level you want in arr2, in case you find, you should return the object, for example :

 let arr1 = [{"LEVEL":1},{"LEVEL":2},{"LEVEL":3,"POSITION":"FCONTROLLER"}, 
            {"LEVEL":4,"POSITION":"RGM"},{"LEVEL":5,"POSITION":"GM"},{"LEVEL":5,"POSITION":"GMH"},{"LEVEL":6},{"LEVEL":7,"POSITION":"EGM"}]

 let arr2 = [1,3,5]

const output =arr1.filter((item) => {
  return arr2.indexOf(item.LEVEL) !== -1
});

It will return every object that object.LEVEL is in arr2.

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

2 Comments

But I do not want LEVEL 1 as it doesnt have position
You can use : return (arr2.indeOf(item.LEVEL) !== -1) && (item.POSITION)
1

While reducing arr1, check if the current object has a POSITION value, and if its LEVEL is included in arr2. If both are true push it to the accumulator:

const arr1 = [{"LEVEL":1},{"LEVEL":2},{"LEVEL":3,"POSITION":"FCONTROLLER"}, 
            {"LEVEL":4,"POSITION":"RGM"},{"LEVEL":5,"POSITION":"GM"},{"LEVEL":5,"POSITION":"GMH"},{"LEVEL":6},{"LEVEL":7,"POSITION":"EGM"}]

const arr2 = [1,3,5]

const result = arr1.reduce((r, o) => {
  if(o.POSITION && arr2.includes(o.LEVEL)) {
    r.push(o.POSITION)
  }
  
  return r
}, [])

console.log(result)

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.