Open In App

Underscore.js _.keep() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The _.keep() method takes an array and a function and hence returns an array generated which keeps only true values based on the conditions of the function.

Syntax:

_.keep(array, function)

Parameters:

  • array: The given array from which the keep array is created.
  • function: The function containing the conditions for elements to be kept.

Return Value: This method returns a newly created array.

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 create an array by keeping all positive values.

javascript




// Defining underscore contrib variable
const _ = require('underscore-contrib');
// Array
let array = [-1, -21, -43, 34, 12, -1];
// Getting keep array using keep() method
let k_array = _.keep(array, function (x) {
    if (x > 0) {
        return x;
    }
});
console.log("Original Array : ", array);
console.log("Generated keep Array : ", k_array);


Output:

Original Array :  [ -1, -21, -43, 34, 12, -1 ]
Generated keep Array :  [ 34, 12 ]

Example 2: In this example, we will create an array by keeping all negative values.

javascript




// Defining underscore contrib variable
const _ = require('underscore-contrib');
// Array
let array = [-1, -21, -43, 34, 12, -1];
// Getting keep array using keep() method
let k_array = _.keep(array, function (x) {
    if (x < 0) {
        return x;
    }
});
console.log("Original Array : ", array);
console.log("Generated keep Array : ", k_array);


Output:

Original Array :  [ -1, -21, -43, 34, 12, -1 ]
Generated keep Array :  [ -1, -21, -43, -1 ]

Example 3: In this example, we will create an array by keeping all multiples of 5.

javascript




// Defining underscore contrib variable
const _ = require('underscore-contrib');
// Array
let array = [-1, -25, -43, 10, 125, -1];
// Getting keep array using keep() method
let k_array = _.keep(array, function (x) {
    if (x % 5 == 0) {
        return x;
    }
});
console.log("Original Array : ", array);
console.log("Generated keep Array : ", k_array);


Output:

Original Array :  [ -1, -25, -43, 10, 125, -1 ]
Generated keep Array :  [ -25, 10, 125 ]


Last Updated : 05 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads