Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Underscore.js | _.keepIndexed() Method

  • Last Updated : 29 Jul, 2020

The Underscore.js _.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:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

_.keepIndexed(array, function)

Parameters:

  • array: The array passed to be passed to this method.
  • function: 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 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 generate an array using this method by checking conditions.

Here, in the function, the index of the array is passed which is further used to get values and comparison.




// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
// Defining Array
var array = [1, 3, 5, 9]
// Using 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.




// Defining underscore contrib variable
var _ = require('underscore-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 if condition to get particular values.




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

Output:

Generated Array :
[ 11 ]



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!