Underscore.js | _.keepIndexed() Method

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 variableconst _ = require('underscore-contrib');// Defining Arraylet array = [1, 3, 5, 9]// Using keepIndexed() Methodarr = _.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 variableconst _ = require('underscore-contrib');// Defining Arraylet array = [1, 3, 5, 9, 11, 22, 34, 55]// Using keepIndexed() Methodarr = _.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 variableconst _ = require('underscore-contrib');// Defining Arraylet array = [1, 3, 5, 9, 11, 22, 34, 55]// Using keepIndexed() Methodarr = _.keepIndexed(array, function (n) {Ā Ā Ā Ā if (n === 4) return array[n];});Ā
console.log("Generated Array : ");console.log(arr); |
Output:
Generated Array : [ 11 ]



