Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is the importance of _.initial() function in JavaScript?
The _.initial() function is part of the Underscore.js library that returns all elements of an array except the last n elements. It's useful for removing elements from the end of an array without modifying the original array.
Syntax
_.initial(array, n);
Parameters
array - The input array from which to extract elements.
n (optional) - Number of elements to exclude from the end. Default is 1.
Return Value
Returns a new array containing all elements except the last n elements.
Example: Basic Usage
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
</head>
<body>
<script type="text/javascript">
// Remove last element (default behavior)
let result1 = _.initial([1, 2, 3, 4, 5]);
document.write("Original array: [1, 2, 3, 4, 5]<br>");
document.write("Result: " + result1);
</script>
</body>
</html>
Original array: [1, 2, 3, 4, 5] Result: 1,2,3,4
Example: Removing Multiple Elements
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
</head>
<body>
<script type="text/javascript">
// Remove last 3 elements
let result = _.initial([1, 2, 3, 4, 5], 3);
document.write("Original array: [1, 2, 3, 4, 5]<br>");
document.write("Remove last 3 elements: " + result);
</script>
</body>
</html>
Original array: [1, 2, 3, 4, 5] Remove last 3 elements: 1,2
Common Use Cases
The _.initial() function is commonly used for:
- Removing the last item from breadcrumb navigation
- Processing file paths by removing the filename
- Creating pagination by excluding certain elements
- Data processing where trailing elements need to be ignored
Comparison with Native JavaScript
| Method | Code | Modifies Original? |
|---|---|---|
| _.initial() | _.initial(arr, n) |
No |
| Array.slice() | arr.slice(0, -n) |
No |
| Array.pop() | arr.pop() |
Yes |
Conclusion
The _.initial() function provides a clean, readable way to exclude elements from the end of an array. It's particularly useful when you need to preserve the original array while working with a subset of its elements.
Advertisements
