-2

I am a newbie to JavaScript, and now trying to find a way to filter a string array based on a boolean array.

Given

arr1 = ["Apple", "Banana", "Orange"]
arr2 = [false, true, false]

The expected output is:

["Banana"]

I tried

arr1.filter(item => arr2[item])

but it didn't work. Could you please figure out where I was wrong and what could be a better solution. Your answers will be highly appreicated.

1

1 Answer 1

2

You can get the index in filter(),then check the value in arr2

enter image description here

let arr1 = ["Apple", "Banana", "Orange"]
let arr2 = [false, true, false]

let result = arr1.filter((e,i) => arr2[i])
console.log(result)

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

2 Comments

Thanks for your prompt answer, which really helps me a lot. May I ask what kind of role "e" play here since it has not been used?
@WenMa e is the iterate element and i is the iterate element index,see the picture or official document,you will find it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.