Manipulating Arrays with dropRightWhile

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to remove elements from the end of an array based on a specified function. The dropRightWhile function will loop through the array and remove elements from the right until the function returns true. The remaining elements of the array will then be returned. This lab will help you understand how to manipulate arrays in JavaScript using higher-order functions.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") subgraph Lab Skills javascript/variables -.-> lab-28280{{"`Manipulating Arrays with dropRightWhile`"}} javascript/data_types -.-> lab-28280{{"`Manipulating Arrays with dropRightWhile`"}} javascript/arith_ops -.-> lab-28280{{"`Manipulating Arrays with dropRightWhile`"}} javascript/comp_ops -.-> lab-28280{{"`Manipulating Arrays with dropRightWhile`"}} javascript/loops -.-> lab-28280{{"`Manipulating Arrays with dropRightWhile`"}} javascript/array_methods -.-> lab-28280{{"`Manipulating Arrays with dropRightWhile`"}} end

Dropping Array Elements from Right Based on Function

To drop elements from the end of an array until a certain condition is met, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Loop through the array using Array.prototype.slice() to drop the last element of the array until the passed func returns true.
  3. Return the remaining elements in the array.

Here's an example implementation:

const dropRightWhile = (arr, func) => {
  let rightIndex = arr.length;
  while (rightIndex-- && !func(arr[rightIndex]));
  return arr.slice(0, rightIndex + 1);
};

You can use this function like this:

dropRightWhile([1, 2, 3, 4], (n) => n < 3); // [1, 2]

Summary

Congratulations! You have completed the Drop Array Elements From the Right Based on Function lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like