Open In App

Underscore.js _.interpose() Method

Last Updated : 05 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The _.interpose() Method takes an array and an element and returns a new array with the given element inserted in between every element of the original array.

Syntax:

_.interpose(array, element)

Parameters: 

  • array: The array in which an element is to be inserted.
  • element: The element to be inserted between every other element.

Return Value: This method returns a newly created interposed array.

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 create a new array using this method.

javascript




// Defining underscore contrib variable
const _ = require('underscore-contrib');
// Array
let arr = [8, 8, 8, 8, 8, 8];
// Element
let ele = 0
// Constructing interposed array
let i_arr = _.interpose(arr, ele);
console.log("Array : ");
console.log(arr);
console.log("Element : ");
console.log(ele);
console.log("Interposed array : ");
console.log(i_arr);


Output:

Array :
[ 8, 8, 8, 8, 8, 8 ]
Element :
0
Interposed array :
[
  8, 0, 8, 0, 8,
  0, 8, 0, 8, 0,
  8
]

Example 2: If there are no betweens, then the original array is returned.

javascript




// Defining underscore contrib variable
const _ = require('underscore-contrib');
// Array
let arr = [8];
// Element
let ele = 0
// Constructing interposed array
let i_arr = _.interpose(arr, ele);
console.log("Array : ");
console.log(arr);
console.log("Element : ");
console.log(ele);
console.log("Interposed array : ");
console.log(i_arr);


Output: Here, the chunk array is compensated due to the shortage of elements.

Array :
[ 8 ]
Element :
0
Interposed array :
[ 8 ]

Example 3: For an empty array, the same empty array is returned.

javascript




// Defining underscore contrib variable
const _ = require('underscore-contrib');
// Array
let arr = [];
// Element
let ele = 0
// Constructing interposed array
let i_arr = _.interpose(arr, ele);
console.log("Array : ");
console.log(arr);
console.log("Element : ");
console.log(ele);
console.log("Interposed array : ");
console.log(i_arr);


Output: Here, the chunk array is compensated due to the shortage of elements.

Array :
[ 0 ]
Element :
0
Interposed array :
[ 0 ]


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads