The Lodash _.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: This method takes two parameters as mentioned above and described below:
- array: The given array from which 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 lodash contrib library to be installed.
Module Installation: Lodash contrib library can be installed using the following command:
npm install lodash-contrib –save
Example 1: In this example, we will create an array by keeping all positive values.
// Defining lodash contrib variable var _ = require( 'lodash-contrib' ); // Array var array = [-1, -21, 43, 34, 12, -1]; // Getting keep array using keep() method var 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 : [ 43, 34, 12 ]
Example 2: In this example, we will create an array by keeping all negative values.
// Defining lodash contrib variable var _ = require( 'lodash-contrib' ); // Array var array = [-1, -21, -43, 34, 12, -1]; // Getting keep array using keep() method var 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 2.
// Defining lodash contrib variable var _ = require( 'lodash-contrib' ); // Array var array = [-1, -25, -43, 10, 125, -1]; // Getting keep array using keep() method var k_array =_.keep(array, function (x) { if (x % 2 == 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 : [ 10 ]