Open In App

Underscore.js | _.keepIndexed() Method

Last Updated : 05 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 acting upon the elements of the given array.

Syntax:

_.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.

javascript




// Defining underscore contrib variable
const _ = require('underscore-contrib');
// Defining Array
let 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.

javascript




// Defining underscore contrib variable
const _ = require('underscore-contrib');
// Defining Array
let 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 underscore contrib variable
const _ = require('underscore-contrib');
// Defining Array
let 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 ]


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads