2

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

5
  • 1
    Are you saying, you would like the second array to keep getting looped over, so if you had a, b, c, d, e, f you would get a 1, b 2, c 1, d 2, e 1, f 2?? Commented Feb 3, 2017 at 13:25
  • where did b came from ? Commented Feb 3, 2017 at 13:30
  • 1
    @CallumLinington yes Commented Feb 3, 2017 at 13:37
  • @VinodLouis, sorry was a typo Commented Feb 3, 2017 at 13:37
  • I kind of think what is the point, zip code isn't difficult... you might as well implement the function yourself... Commented Feb 3, 2017 at 13:55

2 Answers 2

3

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>

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

1 Comment

Very nice. You could even replace the slice with take(arr1.length) to have one less parameter.
1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.