Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptUnderscore.js _.keep() Method

Underscore.js _.keep() Method

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 ]

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments