Is there a way in lodash to zip two arrays of different size, where the result would like this
_.zip(['a', 'b', 'c'], [1,2]) -> [['a', 1], ['b', 2], ['c', 1]]
So it should start just from the beginning if one array reach its end
You can create a new array, in which the 2nd array will be repeated, and then _zip() it with the original array.
The example assumes that the 2nd array is the shorter one.
function repeatingZip(arr1, arr2) {
var ratio = Math.ceil(arr1.length / arr2.length); // how many times arr2 fits in arr1
var pattern = _(new Array(ratio)) // create a new array with the length of the ratio
.fill(arr2) // fill each item with the 2nd array
.flatten() // flatten it to an array
.take(arr1.length) // remove redundant items
.value();
return _.zip(arr1, pattern);
}
var result = repeatingZip(['a', 'b', 'c', 'd', 'e'], [1,2]);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
slice with take(arr1.length) to have one less parameter.You can use the _.zipWith function that allows you to modify the result of zip.
You can then sort out the size problem in a number of ways. In this one, I calculate the size difference and use it to provide a value when the function callback gets an undefined value (this happens when the size of one of the arrays is exceeded).
var idxWrp = function(arr1, arr2) {
var index = 0,
diff = Math.abs(_.size(arr1) - _.size(arr2)) - 1;
return function(a, b) {
a = _.isUndefined(a) ? arr1[index % diff] : a;
b = _.isUndefined(b) ? arr2[index % diff] : b;
index++;
return [a, b];
};
},
arr1 = [1, 2, 3],
arr2 = [1, 2, 3, 4, 5, 6, 7],
res = _.zipWith(arr1, arr2, idxWrp(arr1, arr2));
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
a, b, c, d, e, fyou would geta 1, b 2, c 1, d 2, e 1, f 2??