Reputation: 741
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), [])
Upvotes: 0
Views: 477
Reputation: 47
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.
Upvotes: 1
Reputation: 191946
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)
Upvotes: 1