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
What is the importance of _without() method in JavaScript?
The _.without() method is part of the Underscore.js library that creates a new array by excluding specified values from an original array. It performs case-sensitive matching and removes all occurrences of the specified values.
Syntax
_.without(array, *values)
Parameters
- array - The source array to filter
- *values - One or more values to exclude from the array
Return Value
Returns a new array with the specified values removed, preserving the original array order.
Example: Removing Numbers
The following example removes multiple numeric values from an array:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.1/underscore-min.js"></script>
</head>
<body>
<script>
var numbers = [5, 6, 4, 8, 9, 9, 0, 1];
var result = _.without(numbers, 0, 9, 1);
document.write("Original: " + numbers + "<br>");
document.write("Result: " + result);
</script>
</body>
</html>
Original: 5,6,4,8,9,9,0,1 Result: 5,6,4,8
Example: Case Sensitivity
This example demonstrates that _.without() is case-sensitive when comparing strings:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.1/underscore-min.js"></script>
</head>
<body>
<script>
var languages = [5, 6, "c++", "php", "java", "javascript", 0, 1];
var filtered = _.without(languages, 0, "JAVA", 1);
document.write("Original: " + languages + "<br>");
document.write("Filtered: " + filtered + "<br>");
document.write("Note: 'java' remains because 'JAVA' != 'java'");
</script>
</body>
</html>
Original: 5,6,c++,php,java,javascript,0,1 Filtered: 5,6,c++,php,java,javascript Note: 'java' remains because 'JAVA' != 'java'
Key Points
- Creates a new array without modifying the original
- Removes all occurrences of specified values
- Performs strict equality comparison (===)
- Case-sensitive for string comparisons
- Can accept multiple values to remove
Browser Compatibility
Requires Underscore.js library to be loaded. Works in all browsers that support JavaScript ES3 and above.
Conclusion
The _.without() method provides a clean way to filter arrays by excluding specific values. Remember that it's case-sensitive and creates a new array rather than modifying the original.
