Topic Description

Create a dropRightWhile function that takes two parameters:

The dropRightWhile function should iterate from the end of the array and remove elements that satisfy the specified condition until it encounters an element that does not meet the condition. It should then return a new array containing the remaining elements, ensuring that the original array remains unchanged.

console.log(dropRightWhile(['hello', 'world', 'today', 'isGood'], (value) => value.length > 5)); // => ['hello', 'world', 'today']

console.log(dropRightWhile([ { name: 'Alice', age: 25 }, { name: 'Charlie', age: 20 }, { name: 'Bob', age: 30 }, ], (obj) => obj.age > 25)) // => [{ name: 'Alice', age: 25 }, { name: 'Charlie', age: 20 }]

console.log(dropRightWhile([10, 20, 30, 40, 50, 10], (value) => value !== 10)) // => [10, 20, 30, 40, 50, 10]

console.log(dropRightWhile([1], (value) => value > 0)) // => []

Answer


function dropRightWhile(arr,predicate){
	let index = arr.length - 1
	for(let i = arr.length-1; i >= 0; i--){
		if( !predicate(arr[i]) ){
			break
		}else{
			index--
		}
	}
	return arr.slice(0,index+1)
}
function dropRightWhile(array, predicate) {
  let index = array.length-1

  while (index >=0 && predicate(array[index])) {
    index-- 
  }

  return array.slice(0,index+1)
}