1

I wanted to remove trailing empty elements and Carriage Return from Array. For example my array looks like this:

Input arr: ['', 'Apple', '', 'Banana', '', 'Guava', '', '', '', '\r']

Required Output: ['', 'Apple', '', 'Banana', '', 'Guava']

Definition of trailing empty elements : After the last valid element ('Guava' in this case), there will not be any other valid element.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
EagleXiV
  • 23
  • 2

5 Answers5

1

I don't think there's any magic bullet here, just a loop checking for the values you want to remove, directly or with a regular expression. For instance, to remove blank strings and "\r":

while (array.length) {                      // Loop while there are still entries
    const last = array[array.length - 1];   // Get the last entry without removing it
    if (last !== "" && last !== "\r") {     // Is this one to remove?
        break;                              // No, stop
    }
    --array.length;                         // Yes, remove and keep looping
}

Live Example:

const array = ['', 'Apple', '', 'Banana', '', 'Guava', '', '', '', '\r'];
while (array.length) {                      // Loop while there are still entries
    const last = array[array.length - 1];   // Get the last entry without removing it
    if (last !== "" && last !== "\r") {     // Is this one to remove?
        break;                              // No, stop
    }
    --array.length;                         // Yes, remove and keep looping
}

console.log(array);

Or to remove all trailing entries with strings consistent just of whitespace, same concept:

while (array.length) {
    if (/\S/.test(array[array.length - 1])) { // \S is "not whitespace"
        break;
    }
    --array.length;
}

That sees if the last entry has any non-whitespace character anywhere, and stops if it finds one.

Live Example:

const array = ['', 'Apple', '', 'Banana', '', 'Guava', '', '', '', '\r'];
while (array.length) {
    if (/\S/.test(array[array.length - 1])) {
        break;
    }
    --array.length;
}

console.log(array);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

You can find the last index using a findLastIndex() function (based on this answer), and then slice the array from 0 to last index + 1:

const arr = ['', 'Apple', '', 'Banana', '', 'Guava', '', '', '', '\r'];

function findLastIndex(array, predicate) {
  const index = array.slice().reverse().findIndex(predicate);
  return index >= 0 ? array.length - 1 - index : index;
};

const result = arr.slice(0, findLastIndex(arr, o => o !== '' && o !== '\r') + 1);

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

There are many ways to tackle this problem, here's a way that uses the built-in Array.prototype.reduceRight() method to locate the last valid element.

const inputArr = ['', 'Apple', '', 'Banana', '', 'Guava', '', '', '', '\r'];
const resultArr = [...inputArr];

// determinines if array element is valid
const isValid = el => (typeof el === 'string') && el.length && el !== '\r';

// find last valid element
const lastValid = resultArr.reduceRight((iValid, curr, index) => {
  return iValid ||
    (isValid(curr) ? index : undefined);
 }, undefined);

// truncate the array
if (lastValid !== undefined) {
  resultArr.length = lastValid + 1;
}

console.log(JSON.stringify(resultArr));
terrymorse
  • 6,771
  • 1
  • 21
  • 27
0

One could utilize reduceRight in a way that a reducer function collects any array item without further validation as soon as the first valid item (... starting the iteration from an array's end ...) was found.

The start value will be a collector object which features and keeps track of all information that are necessary to the reducer function, including the list object where all the passing array items will be collected ...

function collectValidItemFromRight(collector, item) {
  if (collector.isSkipValidation === true) {

    collector.list.unshift(item);
    
  } else if (collector.isValidItem(item)) {

    collector.list.unshift(item);
    collector.isSkipValidation = true;
  }
  return collector;
}

console.log(
  ['', 'Apple', '', 'Banana', '', 'Guava', '', '', '', '\r']
    .reduceRight(collectValidItemFromRight, {

      isValidItem: item => (item !== '') && (item !== '\r'),
      list: [],

    }).list
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
0

let arr =['', 'Apple', '', 'Banana', '', 'Guava', '', '', '', '\r'];

function remove(array){
  let newArray = [];
  let temp = array.join('').replace(/(\r)/, "").split(/(?=[A-Z])/);
  temp.forEach(item=>{
    newArray.push('',item);
  });
  return(newArray);
}
console.log(remove(arr));// prints ["", "Apple", "", "Banana", "", "Guava"]

What the function does:

  1. Creates an new empty array.
let newArray = [];
  1. Join the array to create a string, then replaces the Carriage Return in "" and splits the string on upperCase characters.
let temp = array.join('').replace(/(\r)/, "").split(/(?=[A-Z])/);
  1. Iterates on the temp array elements and pushs to newArray an "" char and the element from temp array.
temp.forEach(item=>{
    newArray.push('',item);
  });
Olga.1992
  • 11
  • 3
  • The above approach fails for string values which contain whitespaces like within `'Banana Shake'` as of e.g. this array ... `['', 'Apple', '', 'Banana Shake', '', 'Guava', '', '', '', '\r'];` – Peter Seliger Jan 21 '21 at 18:12