Skip to content
Related Articles

Related Articles

Lodash | _.zipWith() Method
  • Last Updated : 08 May, 2020

The _.zipWIth() method is used to combine arrays into one array by applying function in the same value at the same index of arrays first the function is applied on the first value of the array and then returned value is added into a new array first value and same for the second, third and so on. If you don’t pass the function it will simply work as zip.

Syntax:

_.zipWith(arrays, [iteratee=_.identity])

Parameters: This method accepts two or more parameters as mentioned above and described below:

  • arrays: This parameter holds one or more array that need to process.
  • [iteratee=_.identity]: This parameter holds the function to combine grouped values.

Return Value: This method returns an array after applying function on the given array.

Example 1:






const _ = require('lodash');
  
let x = [10, 20, 30];
  
let y = [100, 200, 300];
  
let combinedArray = _.zipWith(x, y, function(a, b) {
    return a + b;
});
  
console.log(combinedArray);

Here, const _ = require('lodash') is used to import the lodash library into the file.

Output:

[ 110, 220, 330 ]

Example:




const _ = require('lodash');
  
let x = [10, 20, 30];
  
let y = [100, 200, 300];
  
let z = [1000, 2000, 3000];
  
let combinedArray = _.zipWith(x, y, z, function(a, b, c) {
    return a + b + c;
});
  
console.log(combinedArray);

Output:

[ 1110, 2220, 3330 ]

Example:




const _ = require('lodash');
  
let firstname = ['Rahul', 'Ram', 'Aditya'];
  
let lastname = ['Sharma', 'Kumar', 'Verma'];
  
  
let fullname = _.zipWith(firstname, lastname, function(a, b) {
    return a + ' ' + b;
});
  
console.log(fullname);

Output:

[ 'Rahul Sharma', 'Ram Kumar', 'Aditya Verma' ]

Example: If you don’t pass function, it will work same as _.zip().




const _ = require('lodash');
  
let x = [10, 20, 30];
  
let y = [100, 200, 300];
  
let z = [1000, 2000, 3000];
  
let combinedArray = _.zipWith(x, y, z);
  
console.log(combinedArray);

Output:

[ [ 10, 100, 1000 ], [ 20, 200, 2000 ], [ 30, 300, 3000 ] ]

Note: This will not work in normal JavaScript because it requires the library lodash to be installed.

Reference: https://lodash.com/docs/4.17.15#zipWith

My Personal Notes arrow_drop_up
Recommended Articles
Page :