0

Is there a function similar to map() that can take more then one array as input.

I am talking about something like this:

arr1 = [0,1,2];
arr2 = [2,4,6];

result = [arr1, arr2].multiMap((item1, item2) => item1 + item2);

console.out(result);

// output: [2,5,8] 

I'm sure that it should exist, but I just cant find it.

3
  • 1
    No, it doesn't exist. It can be trivially implemented using map, though or using a third party library, if you wish. Commented Jan 9, 2020 at 12:16
  • pretty easy solution with simple for loop... no need to complicate it Commented Jan 9, 2020 at 12:16
  • @JurajKocan, Thank you for the sugestion. I know it can be done, but I was looking for a more compact and readable solution. Commented Jan 9, 2020 at 12:28

1 Answer 1

1

Not directly. But map function's callback gets three parameters, not just one, and the second one is the index, which you can use to get the corresponding elements of parallel arrays. (The third one is the array itself, and can be ignored.)

result = arr1.map((item1, i) => item1 + arr2[i])

or more readably and sliiiightly less performantly

result = arr1.map((_, i) => arr1[i] + arr2[i])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.