Question: I have an array of strings. Some of elements are empty, i.e. `''` (there are no `null`, `undefined` or strings containing only white space characters). I need to remove these empty elements, but only from the (right) end of array. Empty elements that come before non-empty elements should remain. If there are only empty strings in array, empty array should be returned.

Below is the code I have so far. It works, but I wonder - is there a way that does not require all these `if`s? Can I do it without creating in-memory copy of array?

```
function removeFromEnd(arr) {
    t = [...arr].reverse().findIndex(e => e !== '');

    if (t === 0) {
        return arr;
    } else if (t === -1) {
        return [];
    } else {
        return arr.slice(0, -1 * t);
    }
}

```

Test cases
----------

```
console.log(removeFromEnd(['a', 'b', '', 'c', '', '']));
console.log(removeFromEnd(['a', '', '']));
console.log(removeFromEnd(['', '', '', '', 'c']));
console.log(removeFromEnd(['', '', '', '']));

```

```
[ 'a', 'b', '', 'c' ]
[ 'a' ]
[ '', '', '', '', 'c' ]
[]

```

Answer: 
You could do this with `reduceRight` and change one value when you find first elements that is not empty string.

```js
function removeFromEnd(arr) {
  return arr.reduceRight((r, e) => {
    if (e) r.match = true;
    if (r.match) r.arr.unshift(e)
    return r;
  }, {arr: []}).arr
}

console.log(removeFromEnd(['a', 'b', '', 'c', '', '']));
console.log(removeFromEnd(['a', '', '']));
console.log(removeFromEnd(['', '', '', '', 'c']));
console.log(removeFromEnd(['', '', '', '']));
```
> 
> is there a way that does not require all these ifs? Can I do it without creating in-memory copy of array?
> 
> 
> 

Probably not very functional, but a very straight forward implementation:

```js
function removeFromEnd(arr) {
    let i = arr.length - 1;

    while (arr[i] === "") i--;

    return arr.slice(0, i + 1);
}

console.log(removeFromEnd(['a', 'b', '', 'c', '', '']));
console.log(removeFromEnd(['a', '', '']));
console.log(removeFromEnd(['', '', '', '', 'c']));
console.log(removeFromEnd(['', '', '', '']));
```

It's hard to find the balance here... You tagged `functional-programming`, and the answer by @naomik shows you a beautiful functional solution that matches both the tag and the concern in the quote.

If you're just looking to simplify and optimize, my snippet here might just be enough...