Open In App

Underscore.js _.dropWhile() Method

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

The _.dropWhile() method takes an array and a function and hence returns an array in which elements are dropped from the original array for which the function returns true.

Note: values are dropped until the function returns false, after a false value no changes to the original value are made.

Syntax:

_.dropWhile(array, function)

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

  • array: The given array from which dropped array is created.
  • function: The function containing the conditions for elements to be dropped.

Return Value: This method returns a newly created 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

Example 1: In this example, we will create an array with all positive values dropped.

Javascript




// Defining underscore contrib variable
const _ = require('underscore-contrib');
// Array
let array = [11, 21, 43, 34, 12, -1];
// Getting dropped array using dropWhile() method
let d_array = _.dropWhile(array, function (x) {
    return x > 0;
});
console.log("Array : ", array);
console.log("Dropped Array : ", d_array);


Output:

Array :  [ 11, 21, 43, 34, 12, -1 ]
Dropped Array :  [ -1 ]

Example 2: In this example, we will create an array with all negative values dropped.

Javascript




// Defining underscore contrib variable
const _ = require('underscore-contrib');
// Array
let array = [-1, -21, -43, 34, 12, -1];
// Getting dropped array using dropWhile() method
let d_array = _.dropWhile(array, function (x) {
    return x < 0;
});
console.log("Array : ", array);
console.log("Dropped Array : ", d_array);


Output: negative values are dropped until a positive value comes.

Array :  [ -1, -21, -43, 34, 12, -1 ]
Dropped Array :  [ 34, 12, -1 ]

Example 3: In this example, we will create an array with 0 values dropped until the function returns false.

Javascript




// Defining underscore contrib variable
const _ = require('underscore-contrib');
// Array
let array = [0, 0, 0, 0, 0, -1, -21, -43, 34, 12, -1];
// Getting dropped array using dropWhile() method
let d_array = _.dropWhile(array, function (x) {
    return x == 0;
});
console.log("Array : ", array);
console.log("Dropped Array : ", d_array);


Output: 

Array :  [
   0,   0,   0,  0,  0,
  -1, -21, -43, 34, 12,
  -1
]
Dropped Array :  [ -1, -21, -43, 34, 12, -1 ]


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

Similar Reads