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)
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]]))
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With