Open In App

Remove an Item from Array using UnderscoreJS

Last Updated : 24 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Underscore.js is a JavaScript library that provides a wide range of utility functions for working with arrays, objects, functions, and more. One common task when working with arrays is removing an item based on a specific condition. In this article, we will explore options to remove an item from an array using Underscore.js.

Approach 1: Using _.without() Method

The _.without() method creates a new array with all occurrences of a specified value removed.

HTML
<!DOCTYPE html>
<html>

<head>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
    </script>
</head>

<body>
    <script>
        let array = [1, 2, 3, 4, 5];
        let newArray = _.without(array, 3);
        console.log(newArray);
    </script>
</body>

</html>

Output: This output will display on console.

[1, 2, 4, 5]

Approach 2: Using _.filter() Method

The _.filter() method creates a new array with all elements that pass the test implemented by the provided function.

HTML
<!DOCTYPE html>
<html>

<head>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
    </script>
</head>

<body>
    <script>
        let array = [1, 2, 3, 4, 5];
        let newArray = _.filter(array, function(item) {
            return item !== 3;
        });
        
        console.log(newArray);
    </script>
</body>

</html>

Output:

[1,2,4,5]

Approach 3: Using _.reject() Method

The _.reject() method is the opposite of _.filter(), creating a new array with all elements that do not pass the test implemented by the provided function.

HTML
<!DOCTYPE html>
<html>

<head>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
    </script>
</head>

<body>
    <script>
        let array = [1, 2, 3, 4, 5];
        let newArray = _.reject(array, function(item) {
            return item === 3;
        });
        console.log(newArray);
    </script>
</body>

</html>

Output:

[1,2,4,5]


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

Similar Reads