0

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.

1
  • I would think you could try a regular expression. Perhaps someone knows the exact syntax. Commented Jan 21, 2021 at 16:22

6 Answers 6

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);

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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));

Comments

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);
  });

1 Comment

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'];
0

The initial value -1 is needed in case all array elements happen to be empty.

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

const discard = v => 
    v === "" || typeof v === "undefined" || 
    v === null || v == '\r' ;

arr.length = arr.reduce(
    (accu, value, index) => 
    (discard(value) ? accu : index), -1) + 1 ;

console.log(arr);

Comments

-1

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; }

1 Comment

Whoever did the -1 might consider providing a technical reason which qualifies the implementation/approach as downvote worthy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.