Lodash _.splitAt() Method
Last Updated :
23 Sep, 2020
The Lodash _.splitAt() method takes an array and a numeric index and returns a new array containing two embedded arrays made by splitting the original array at the provided numeric index.
Syntax:
_.splitAt(array, numeric_index)
Parameters: This method takes two parameters as mentioned above and described below:
- 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 lodash contrib library to be installed. lodash contrib library can be installed using npm install lodash-contrib –save.
Example 1: In this example, we will split an array using this method at the 4th index.
Javascript
var _ = require( 'lodash-contrib' );
var array = [1, 3, 6, 8, 9, 11, 3];
var value = 4;
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 : 4
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 one empty and the other same as the original array.
Javascript
var _ = require( 'lodash-contrib' );
var array = [1, 3, 6, 8, 9, 11, 3];
var value = 0;
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
var _ = require( 'lodash-contrib' );
var array = [1, 3, 6, 8, 9, 11, 3];
var value = 20;
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
], [] ]
Share your thoughts in the comments
Please Login to comment...