Removing Array Elements Using Callback

Beginner

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

Introduction

In this lab, we will be working on a JavaScript programming challenge that involves manipulating arrays. The goal of this lab is to write a function that removes elements from the end of an array until a specific condition is met, and returns the removed elements. You will be using various JavaScript array methods and a callback function to complete this challenge.

Removing Array Elements From the End Until a Condition Is Met

To start practicing coding, open the Terminal/SSH and type node.

Here's a function that removes elements from the end of an array until the passed function returns false. It then returns the removed elements.

To use it, create a reversed copy of the array using the spread operator (...) and Array.prototype.reverse(). Then, loop through the reversed copy using a for...of loop over Array.prototype.entries() until the returned value from the function is falsy.

The callback function, fn, accepts a single argument which is the value of the element. Finally, return the removed elements using Array.prototype.slice().

const takeRightWhile = (arr, fn) => {
  for (const [i, val] of [...arr].reverse().entries())
    if (!fn(val)) return i === 0 ? [] : arr.slice(-i);
  return arr;
};

Here's an example of how to use the function:

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

Summary

Congratulations! You have completed the Remove Array Elements From the End While Condition Is Met lab. You can practice more labs in LabEx to improve your skills.