Can I use map function with 2 arrays?

1.1k Views Asked by At

I was wondering if any function exist that can do something like that

I already tried zipWith and some variations of the map, but no good results. Only working solution to this is 2x ForEach, but I was wondering if I can minimalize this to one function

_.map( (array1, array2), function(knownValue, indexOfArray1, indexOfArray2) );

What I need is to increase array1 and array 2 indexes simultaneously (like: a1: 1, a2: 1; a1: 2, a2: 2; ...).

This arrays have also other types of values

@EDIT

I messed a little. What i really wanted is to make this wrongly writed code to work

_.map( (array1, array2), (valueOfArray1, valueOfArray2), someFunction(knownValue, valueOfArray1, valueOfArray2) );

So my intention is: For array1 and array2 elements, execute the function "someFunction", and in the next increment, use the next element of each array.

Like :

_.map( (array1, array2), (array1[0], array2[0]), someFunction(knownValue, array1[0], array2[0]) );

and next

_.map( (array1, array2), (array1[1], array2[1]), someFunction(knownValue, array1[1], array2[1]) );

but I want it more elegant :P

PS (Sorry for this mess)

3

There are 3 best solutions below

0
Ziv Ben-Or On BEST ANSWER

Here is an example with flatMap:

const arr1 = [1,3,5];
const arr2 = [2,4,6];

console.log(arr1.flatMap((x,i) =>[x, arr2[i]]))

0
jonahe On

Since you already seem to be using lodash (or something similar) the .zip should work. The only pitfall is that .zip produces "pairs" with one from each original array IN a new array.

So when you map over the result from the .zip, the first argument is an array. See the example below and note that I'm destructuring the first argument with

function([a1_item, a2_item], indexForBoth) { .. rest of function here }

const a1 = ['a', 'b', 'c'];
const a2 = ['One', 'Two', 'Three'];

const result = _.zip(a1, a2).map(function([a1_item, a2_item], indexForBoth) { 
  return a1_item + a2_item + indexForBoth;
});


console.log("a1", a1);
console.log("a2", a2);
console.log("a1 zipped with a2", _.zip(a1, a2) );

console.log("Result after mapping and concatinating", result);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

0
adiga On

Since they both have the same number of items, you can loop through array1 using map. The second parameter of map callback is the index. You can use it to get the equivalent value from array2 using array2[index]

array1.map((value1, index) => someFunction(knownValue, value1, array2[index]))

This creates an array of values returned by someFunction for each index

Here's a snippet with some sample data. Here, someFunction concatenates each value with a _ seperator

const someFunction = (...values) => values.join('_')

const array1 = [1, 2, 3],
      array2 = [10, 20, 30],
      knownValue = "fixed";

const output = array1.map((value1, i) => someFunction(knownValue, value1, array2[i]))

console.log(output)