Open In App

Lodash _.keepindexed() Method

Improve
Improve
Like Article
Like
Save
Share
Report

Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.

The _.keepIndexed() method takes an array and a function as parameters and returns a new array filled with the non-null return results of the given function acted upon the elements of the given array.

Syntax:

_.keepIndexed( array, function )

Parameters: This method accepts two parameters as mentioned above and described below:

  • array: This is the array to be passed to this method.
  • function: This is the function containing the conditions to generate a new array.

Return Value: This method returns a newly generated array.

Note: This will not work in normal JavaScript because it requires the lodash-contrib library to be installed. The lodash-contrib library can be installed using npm install lodash-contrib –save.

Example 1: In this example, we will generate an array using this method by checking conditions. The index of the array is passed in the function which is further used to get values and comparison.

Javascript




// Defining Lodash-contrib variable 
const _ = require('lodash-contrib'); 
  
// Defining Array
var array = [1, 3, 5, 9]
  
// Using the _.keepIndexed() Method
arr = _.keepIndexed(array, function(n) { 
     return array[n] >= 5;
});
  
console.log("Generated Array : ");
console.log(arr);


Output:

Generated Array :
[ false, false, true, true ]

Example 2: In this example, we will generate an array full of indexes of elements.

Javascript




// Defining Lodash-contrib variable 
const _ = require('lodash-contrib'); 
  
// Defining Array
var array = [1, 3, 5, 9, 11, 22, 34, 55]
  
// Using _.keepIndexed() Method
arr = _.keepIndexed(array, function(n) { 
  return n;
});
  
console.log("Generated Array : ");
console.log(arr);


Output:

Generated Array :
[
  0, 1, 2, 3,
  4, 5, 6, 7
]

Example 3: In this example, we will use the if condition to get particular values.

Javascript




// Defining Lodash-contrib variable 
const _ = require('lodash-contrib'); 
  
// Defining Array
var array = [1, 3, 5, 9, 11, 22, 34, 55]
  
// Using _.keepIndexed() Method
arr = _.keepIndexed(array, function(n) { 
  if(n===5) return array[n];
});
  
console.log("Generated Array : ");
console.log(arr);


Output:

Generated Array :
[ 22 ]


Last Updated : 14 Sep, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads