Open In App

Underscore.js _.weave() Method

Last Updated : 29 Jul, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The _.weave() method takes two arrays and returns an array with both arrays woven together.

Note: The array returned from _.weave() method will be woven till the shortest array, rest array values are the same.

Syntax:

_.weave(array1, array2)

Parameters: 

  • array1: The first array.
  • array2: The second array.

Return Value: This method returns a woven array made from array1 and array2.

Note: This will not work in normal JavaScript because it requires the underscore.js contrib library to be installed.  Underscore.js contrib library can be installed using npm install underscore-contrib –save.

Example 1: In this example, we will generate a woven array with array1’s and array2’s sizes as same.

Javascript




// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
// Array1
var array1 = [1, 2, 3, 4];
  
// Array2
var array2 = [5, 6, 7, 8]
  
// Generating Array using weave() method
var arr =_.weave(array1, array2);
console.log("Array1 : ", array1);
console.log("Array2 : ", array2);
console.log("Woven Array : ", arr);


Output:

Array1 :  [ 1, 2, 3, 4 ]
Array2 :  [ 5, 6, 7, 8 ]
woven Array :  [
  1, 5, 2, 6,
  3, 7, 4, 8
]

Example 2: When size of array1 < size of array2

Javascript




// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
// Array1
var array1 = [1, 2];
  
// Array2
var array2 = [5, 6, 7, 8]
  
// Generating Array using weave() method
var arr =_.weave(array1, array2);
console.log("Array1 : ", array1);
console.log("Array2 : ", array2);
console.log("Woven Array : ", arr);


Output:

Array1 :  [ 1, 2 ]
Array2 :  [ 5, 6, 7, 8 ]
Woven Array :  [ 1, 5, 2, 6, 7, 8 ]

Example 3: When the size of array1 > size of array2 

Javascript




// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
// Array1
var array1 = [1, 2, 3, 4];
  
// Array2
var array2 = [5, 6]
  
// Generating Array using weave() method
var arr =_.weave(array1, array2);
console.log("Array1 : ", array1);
console.log("Array2 : ", array2);
console.log("Woven Array : ", arr);


Output:

Array1 :  [ 1, 2, 3, 4 ]
Array2 :  [ 5, 6 ]
Woven Array :  [ 1, 5, 2, 6, 3, 4 ]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads