Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptUnderscore.js _.splitAt() Method

Underscore.js _.splitAt() Method

The _.splitAt() method takes an array and a numeric index and returns a new array containing two arrays made by splitting the original array at provided numeric index.

Syntax:

_.splitAt(array, numeric_index)

Parameters: 

  • array: The array to be split.
  • numeric_index: The index at which array is to be split.

Return Value: This method returns a newly created array containing two arrays.

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 split an array using this method at index 3.

Javascript




// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
// Array
var array = [1, 3, 6, 8, 9, 11, 3];
  
// Value
var value = 3;
  
// Generating Array using splitAt() method
var arr =_.splitAt(array, value);
console.log("Array : ", array);
console.log("Numeric Value : ", value);
console.log("Generated Array : ", arr);


Output:

Array :  [
  1,  3, 6, 8,
  9, 11, 3
]
Numeric Value :  3
Generated Array :  [ [ 1, 3, 6 ], [ 8, 9, 11, 3 ] ]

Example 2: In this example, we will split an array using this method at index 0, so will get an empty and one same as the original array.

Javascript




// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
// Array
var array = [1, 3, 6, 8, 9, 11, 3];
  
// Value
var value = 0;
  
// Generating Array using splitAt() method
var arr =_.splitAt(array, value);
console.log("Array : ", array);
console.log("Numeric Value : ", value);
console.log("Generated Array : ", arr);


Output:

Array :  [
  1,  3, 6, 8,
  9, 11, 3
]
Numeric Value :  0
Generated Array :  [ [], [
1, 3, 6, 8,
 9, 11, 3
] ]

Example 3: This method is safe for indexes outside ranges.

Javascript




// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
// Array
var array = [1, 3, 6, 8, 9, 11, 3];
  
// Value
var value = 20;
  
// Generating Array using splitAt() method
var arr =_.splitAt(array, value);
console.log("Array : ", array);
console.log("Numeric Value : ", value);
console.log("Generated Array : ", arr);


Output:

Array :  [
  1,  3, 6, 8,
  9, 11, 3
]
Numeric Value :  20
Generated Array :  [ [
1, 3, 6, 8,
 9, 11, 3
], [] ]

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments