Tips for eliminating empty trailing values and Carriage Returns from a JavaScript array

I needed a way to eliminate empty elements and Carriage Returns from the end of an array. Here's an example of what my array looks like:

Input arr:

['', 'Apple', '', 'Banana', '', 'Guava', '', '', '', '\r']

Desired Output:

['', 'Apple', '', 'Banana', '', 'Guava']

Explanation of trailing empty elements : There are no valid elements following the last one ('Guava' in this instance).

Answer №1

There is no easy solution to this problem, just a simple loop that checks for the specific values you want to eliminate, either directly or using a regular expression. For example, if you want to remove empty strings and "\r":

while (array.length) {                      
    const last = array[array.length - 1];   
    if (last !== "" && last !== "\r") {     
        break;                             
    }
    --array.length;                         
}

Live Example:

const array = ['', 'Apple', '', 'Banana', '', 'Guava', '', '', '', '\r'];
while(array.length) {                     
    const last = array[array.length - 1];   
    if (last !== "" && last !== "\r") {
        break;
    }
    --array.length;
}

console.log(array);

To remove trailing entries consisting only of whitespace characters, you can use the following logic:

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

This code snippet checks if the last entry contains any non-whitespace character and stops as soon as 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);

Answer №2

To determine the final index, utilize the findLastIndex() function (referencing this post), and proceed to slice the array from 0 up to the last index + 1:

const arr = ['', 'Orange', '', 'Grapes', '', 'Mango', '', '', '', '\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);

Answer №3

One effective approach to solving this issue involves utilizing the built-in Array.prototype.reduceRight() method to identify the final valid element.

const inputData = ['', 'Apple', '', 'Banana', '', 'Guava', '', '', '', '\r'];
const outputData = [...inputData];

// checks if array element is valid
const isValidElement = elem => (typeof elem === 'string') && elem.length && elem !== '\r';

// locate last valid element
const lastValidElement = outputData.reduceRight((isValid, current, index) => {
  return isValid ||
    (isValidElement(current) ? index : undefined);
 }, undefined);

// trim the array accordingly
if (lastValidElement !== undefined) {
  outputData.length = lastValidElement + 1;
}

console.log(JSON.stringify(outputData));

Answer №4

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

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

Purpose of the function:

  1. Initialize a new empty array.
let filteredArray = [];
  1. Concatenates the elements of the array into a string, then removes any carriage returns and splits the string at uppercase characters.
let temporaryArray = array.join('').replace(/(\r)/, "").split(/(?=[A-Z])/);
  1. Loop through the elements of the temporary array and add an empty character followed by each element to the filteredArray.
temporaryArray.forEach(item=>{
    filteredArray.push('',item);
  });

Answer №5

Using the reduceRight method, one can implement a logic where a reducer function gathers array items without requiring further validation once it encounters the first valid item (starting from the end of the array).

The starting point for this process is a collector object that stores all the necessary information for the reducer function, including the list where the selected array items are stored...

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Getting user input with JQuery and dynamically updating CSS properties

<img src="purplemoon.png" alt="Purple moon" id="moon-photo" /> <table> <tr> <th colspan="4">Control panel</th> </tr> <tr> <td> <!-- attempting to retrieve value from the input field ...

How can I upload an image file using VueJS and Django Rest Framework?

Hello, I am currently in the process of editing a blog page using VueJS and Django Rest Framework. However, I am facing an issue when trying to upload a photo - I keep receiving an error message stating that "the sent data is not a file." Additionally, I a ...

Will synchronous programming on an Express server prevent other users from accessing the page simultaneously?

Currently working on a simple one-page web app that depends on loading weather data from a file. To avoid multiple HTTP requests for each visitor, I have a separate script refreshing the data periodically. In this particular instance, I am using fs.readFi ...

Why am I getting the error in react-dom.development.js related to my index.js file?

Upon checking the console, the following message is displayed: react-dom.development.js:86 Warning: ReactDOM.render is no longer supported in React 18. Please use createRoot instead. Until you transition to the new API, your application will behave as if i ...

Console log displays varied outputs for identical arrays

Having an array in a static form and one that is filled using the ajax post function, I initially planned to replace the static array with the dynamic one. However, upon closer inspection, it seems that the two arrays are not matching. Array 1 (static) ...

Bundling extraneous server code in client rollup

Can someone help me understand why the following code is being included at the top of my browser bundle by Rollup? It seems like these references are not used anywhere from my entry point. Could it be default includes from node builtins? import require$$0$ ...

Incorporating Material-UI with React Searchkit for a seamless user experience, featuring

I encountered an issue when trying to use both searchkit and material-ui in my React application. The problem arises from the fact that these two libraries require different versions of reactjs. Initially, everything was working fine with just searchkit in ...

Differentiating the angular distinction between setting a variable with ng-click and invoking a function

I've encountered a situation like this before. Let's assume the controller has these variables: $scope.valueArr = ['Hello', 'No', 'Yes']; $scope.myValue = 'Hello'; And there is an ng-repeat as follows: ...

Identifying Hashtags with Javascript

I am trying to identify hashtags (#example) in a string using javascript and convert them to <a href='#/tags/example'>example</a> Currently, I have this code: var text = '#hello This is an #example of some text'; text.r ...

ReactJS instance.render function error: How to solve it?

I encountered a strange error message while working with reactjs, which states that instance.render is not a function in reactjs. Despite my efforts, I have been unable to identify the source of this error. Below are the contents of index.js and search_bar ...

What is the most effective method for incorporating CSS using Javascript to target a specific aria-label attribute?

Is there a way to add a CSS property to a specific tag with a particular aria-label on document load? My goal is to change the flex order of a section to 2. I need help using JavaScript to target the aria-label 'block 1' so I can set the order t ...

Intensive analysis of objects comparing their characteristics

Currently delving into the world of Javascript, I encountered a coding exercise involving a "deepEqual" function that I attempted to write but ultimately struggled with. Even after reviewing the solution, one particular part perplexed me - the for loop, ...

What is the method to disable response validation for image endpoints in Swagger API?

I'm working with a Swagger YAML function that looks like this: /acitem/image: x-swagger-router-controller: image_send get: description: Returns 'image' to the caller operationId: imageSend parameters: ...

What are some methods for singling out a specific table row?

When working on my app, I faced the task of importing a JSON file and displaying its contents in a table with 3 columns. However, there are two main issues that arose: Utilizing array index for the row key is not recommended due to the table also having ...

Blog entries alternating between a pair of distinct hues

I want to create a design where each post container has a different color from the one next to it. Essentially, I would like the containers to alternate between two distinct colors. The left side shows how it currently appears, while the right side depict ...

The integration of the jQuery library within the server side of a Google Apps Container Bound Script

Can the jQuery library be utilized server-side in a Google Apps Script that is Container Bound to a Doc or Sheet? If so, what steps should be taken? In a previous inquiry on Stack Overflow, I sought guidance on incorporating jQuery into a container-bound ...

Converting an HTML form with empty values into JSON using JavaScript and formatting it

While searching for an answer to my question, I noticed that similar questions have been asked before but none provided the solution I need. My situation involves a basic form with a submit button. <form id="myForm" class="vertically-centered"> ...

Tips for getting involved in the Mojito repository on Github for javascript development

Looking for guidance on studying, understanding, and debugging code? I have a good grasp of javascript but unsure where to begin. I am familiar with Github and Mojito, but struggling to contribute to the platform. Any tips on how to get started with Moji ...

Using Vue.js to filter a list based on index matches

I need help with synchronizing two lists. The first list is displayed in a carousel format, and the second list contains details corresponding to each card in the carousel. I have successfully implemented logic to track the current index of the displayed c ...

What is the best way to prevent a draggable div from moving past the edge of the viewport?

My situation involves a draggable div that functions as a popup window when a specific button is clicked. However, I noticed that dragging the div to the end of the viewport allows me to drag it out of the visible area, causing the body of the page to expa ...