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

What is the best way to extract a specific object from an array containing multiple objects?

Upon entry, there is an array with various objects. A function is needed to convert this incoming array of objects into a single object. The goal is to bring it to the desired form using the function provided. var array = [ { k1:v1 }, { k2:v2 }, ...

Updating Jqplot display upon ajax call completion

Currently, I have a Jqplot set up using the AJAX JSON Data Renderer and it's functioning properly. There is a button on the page where users can input new values (updated through ajax) which are then stored in the same DB as the json data source. Whe ...

JavaScript allows for the manipulation of elements within a webpage, which includes accessing elements from one

There is a file that contains a fragment for the navbar. The idea is to have listItems in the navbar, and upon clicking on those listItems, another subnavigationbar should open below it. Below is the code I currently have: <!DOCTYPE html> <html x ...

Activate response upon verifying website link

I am adding functionality to my HTML page where I want certain sections to be visible when the user clicks on a link. Initially, these sections are hidden using the CSS property display: none;. My aim is to make these sections visible when the user clicks ...

What is the reason for calling a multi-dimensional array when it is just a one-dimensional array of references to other one-dimensional

I'm familiar with array references, but in Perl, a multidimensional array is actually a one-dimensional array of references to other one-dimensional arrays. Can someone provide an example to help clarify this concept? ...

angularjs ng-repeat utilizing the index instead of names

Using ng-repat to populate an HTML table with an array has been causing some naming normalization issues for me. Dealing with stubborn users, I am now in search of a quick workaround. Sometimes my array AgendaItems appears as: {"Agenda Item":&q ...

Retrieving object by a value within a nested array in Javascript

I need to retrieve all objects that have a specific 'id' within a nested array. Specifically, I want to find all person objects with hobbies id of 2 (hiking) in the provided sample data. This inquiry tackles the challenge of extracting all value ...

Leveraging AngularJS to send a post request to the server through the $http

Can't seem to find a solution to my Angular issue, despite searching for it extensively? After starting to learn Angular recently, I've put together the following code based on various online resources. Here's the HTML: <div data-ng-ap ...

Creating a material texture with file api in three.js is a straightforward process

I have a vision to create a cutting-edge model browser that allows users to handpick models and textures themselves. In order to achieve this, I am utilizing the File API for smooth file handling. My approach involves using two separate file inputs for rec ...

Steer clear of using multiple returns in a loop in JavaScript by utilizing async/await to eliminate the callback pyramid or callback hell

My code consists of multiple return blocks, such as the SignUp() function. connectors.js const connectors = { Auth: { signUp(args) { return new Promise((resolve, reject) => { // Validate the data if (! ...

Real-time functionality is not supported by Firebase functions

I've set up a firebase query within a method in VueJS: data: {this.todaysEvents}, methods : { getTodaysEvents (day) { this.todaysEvents = [] const events = db.ref('calendar') const query = events.orderByChild('da ...

What steps do I need to take to ensure the progress bar extends all the way to the end of the sn

I am currently facing a challenge where the progress bar line in my message queue does not reach the end of the message before it closes. I have included a brief video showcasing the issue along with the relevant code snippet. Any suggestions or ideas woul ...

Transmit the Boolean value to the controller using ajax requests in asp.net.core with C# programming

Within the view section, there is a form that includes a checkbox input. <div class="checkbox"> <label class="">active</label> <div class="icheckbox_flat-green checked" style="position: relative;"> <input type="checkbox" id="A ...

`returning a functional component directly from a component's event listener`

Recently, I started exploring React and came across an issue with React Router integration. I have a React menu component that includes hyperlinks in a sidenav for navigation to other components. However, the standard React Routing method doesn't see ...

Implementing AJAX mysqli interaction in PHP following the MVC design pattern

Today I'm encountering yet another AJAX-related error. I am in the process of developing a user registration system using AJAX and PHP, following MVC architecture. Previously, I successfully built a login system without AJAX that functions flawlessl ...

Obtain the value of a dynamically selected option

I am facing an issue with my select options where I want the input field to be automatically filled with the 'data-place' value of the selected option whenever it changes. This includes a few dynamic select options. $(function() { // Hand ...

What is the best way to display or hide specific tables depending on the button chosen?

Being fairly new to JavaScript, I find myself unsure of my actions in this realm. I've successfully implemented functionality for three links that toggle visibility between different tables. However, my ideal scenario would involve clicking one link t ...

Steps for saving data to a JSON file in a React application

Looking to update a json file with some data. The current contents of the JSON file are: [{"name":"Flossi","image":"https://robohash.org/istevelitut.png?size=50x50&set=set1","price":49,"info": ...

Trouble with jQuery: Tackling a Basic String and Variable Issue

I'm having trouble incorporating my variable into this specific string: var liPad = 20; $(this).css({'width' : width , 'height' : height, 'padding' : "'0px' + liPad + 'px'"}); The desired outcome is ...

Error encountered while compiling NextJS: Unexpected use of single quotation mark in jsx-quotes

I can't seem to compile my NextJs 13 app without encountering errors. Take a look at my shortened eslintrc.js file below: module.exports = { env: { browser: true, es2021: true, }, extends: [ 'plugin:react/recommended', ...