Eliminating blank elements from arrays using JavaScript

I'm looking for some assistance in deciphering the functionality of my code. I'm trying to create a function that will take a string as input and eliminate all letters, leaving only numbers behind. The goal is to have this function return an array containing all the numbers extracted from the string. With help from stackoverflow, I've managed to come up with the following:

number = "32321FDFDS 44"
arr = number.replace(/[A-Za-z]/g," ").split(" ")

for(var i = arr.length - 1; i >= 0; i--){
     if(arr[i] == "") {
          arr.splice(i, 1);
    }
}

As a result, I get

[ '32321', '44' ]

This output works well for me at the moment. However, I'm puzzled by how arr.splice(i,1) manages to remove empty strings. It doesn't seem logical that it has this effect on the contents of arr. Can someone provide clarification on this?

Answer №1

Example :

if (arr[n] == "") // if the element at index `n` in array `arr` is equal to `""`, then do something

Check out Array.prototype.splice()

Illustrating with a two-item array :

var arr = ["123", ""];
if (arr[0] == "") {
  arr.splice(0,1);
} else {
  console.log(arr); // ["123", ""]
};
if (arr[1] == "") {
  arr.splice(1,1);
  console.log(arr); // ["123"]
};

Answer №2

Contrary to other techniques that produce a fresh array while leaving the original unchanged, the .splice method alters an array by directly modifying it.

When you see the statement arr.splice(i, 1);, it means that starting from index i, one element is removed from array arr. Similarly, if(arr[i] == "") indicates that if the element at index i is an empty string, execute the code inside this conditional block. Consequently, when the condition in the if statement evaluates to true, the corresponding item gets deleted from the array.

Unless you have a specific need to cater to ES3-compatible browsers (like IE8 or older), instead of iterating through the array as shown, consider utilizing the .filter method:

var number = "32321FDFDS 44",
  arr = number.replace(/[A-Za-z]/g," ").split(" ").filter(function (item) {
    return !!item; // all strings except an empty string will coerce to true
  });

console.log(arr);

jsFiddle

If your objective is simply to extract numeric strings from a given string without any additional conditions, a more concise approach would be to split based on one or more non-numeric characters:

var number = "32321FDFDS 44",
  arr = number.split(/\D+/);

// final array contains [ "32321", "44" ]
console.log(arr);

This single-step process eliminates the need to filter out empty strings altogether.

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

Unveiling the power of Axios and Vue in fetching API data: The quest for

I've encountered a problem while trying to integrate my API with Vue/Axios. The issue arises when I attempt to store the data retrieved by Axios into an empty variable within the data object of my component. It throws an "undefined at eval" error. Can ...

Can you please explain the purpose of the mysterious JavaScript function f => f?

Currently, I am utilizing a third-party library that utilizes a function with functions as arguments. During my conditional checks, I determine whether to add a particular function as a parameter or not. However, providing null in these cases results in er ...

Leveraging Express request-specific variables to facilitate logging with correlation IDs

Our node express app is now incorporating correlation id's to link requests together. These id's are sent in the header from other services, and our middleware captures them, creates a bunyan logger with the id, and includes it in the request obj ...

What is the best way to split a one-dimensional array when a certain condition is satisfied?

I have a task to input an array of integers. What I would like is to allow the user to stop entering numbers once they have entered all the required numbers and move on to displaying the input numbers. Below is the code that I have written for this purpo ...

How to use jQuery to remove a class from the last entered data in a form

Reminder: This is a jQuery coding challenge, and I am required to write the validation script without using any plugins or additional modules. I have created a basic form validation script. If a user inputs data that is empty, an appropriate error message ...

"Mongoose Nodejs is throwing an error as it is unable to retrieve the property 'id' from an undefined

I'm currently attempting to retrieve and delete an object from MongoDB, but I keep encountering the following error. Cannot read property 'id' of undefined My goal is to fetch an object by its ID. The ID is crucial in my Schema as I am e ...

What is the process of incorporating HTML into a jQuery program in order to immerse the world in an element?

I am looking to utilize HTML with the value in a checkbox, After adding a shortcode: <label class="HCheck">(this is val 1 )</label> and incorporating jQuery to change it to: <label class="HCheck">(this is val 1 ) ...

Using a customized layout, merge AngularJS into Vaadin

I experimented with integrating an angular JS application into Vaadin by utilizing a custom layout as shown below: VerticalLayout mainLayout = new VerticalLayout(); mainLayout.setMargin(true); mainLayout.setWidth("1380px"); setCompositionRoot( ...

Creating a series of images in JavaScript using a for loop

Currently attempting to create an array of images, but with a large number of images I am looking into using a "for loop" for generation. Here is my current code snippet : var images = [ "/images/image0000.png", "/images/image0005.png", "/ima ...

A guide on incorporating multiple nested loops within a single table using Vue.js

Is it possible to loop through a multi-nested object collection while still displaying it in the same table? <table v-for="d in transaction.documents"> <tbody> <tr> <th>Document ID:</th> &l ...

How can you use React.js to only display "Loading..." on the page while the full name is included in the URL?

I've hit a roadblock while trying to solve this issue. Here's the situation: On the page where I need to display certain information, I intended to showcase the full name of the individual from a previous form submission. However, instead of seei ...

Prevent legend strike-through on click in Vue Chart.js

Recently, I made the transition from vue 2 to vue 3 on my website and part of that process involved updating vue-chartjs and chartjs too. However, after modifying the legend text of my pie chart using the generateLabels option (as seen below), the striket ...

Managing traffic in Google Kubernetes Engine (GKE)

I am encountering an issue with our website deployment on GKE, which consists of 10 pods. When deploying a new version, we use MAXsurge=1 and MAXunavailable=0. Upon trying to access the website during a new deployment, I sometimes only see the header in t ...

Using Vue component with v-model and custom input handler

I'm currently working on creating a wrapper component for an <input/> element in Vue.js. Here is the component code: <template> <div> <input v-bind="$attrs" :value="value" @input="input" /> ... </div> <te ...

Example when a specific $scope.apply() is needed:

I am currently delving into the world of Angular and experimenting with different ways to learn how it functions. One of my projects involves creating a simple application where users can add new entries through an HTML interface, store them in a SQLite da ...

Incorporating Javascript into a <script> tag within PHP - a step-by-step guide

I am trying to integrate the following code into a PHP file: if (contains($current_url, $bad_urls_2)) { echo '<script> $('body :not(script,sup)').contents().filter(function() { return this.nodeType === 3; ...

The ng-scope class in AngularJS is failing to be applied

While exploring the Angular Tutorials, I noticed an interesting detail in their example where the ng-scope CSS class is added to each element with a directive. If you want to check out the tutorial for yourself, here's the link: Angular Tutorial on S ...

When running the command `npm start`, an error message is generated

Hey everyone, I've been trying to learn some basic AngularJS 2.0 skills through a tutorial. Unfortunately, when I tried running the command npm run start, it didn't work as expected. I'm currently using Git Bash on Windows 10 OS. If you hav ...

Different scenarios call for different techniques when it comes to matching text between special characters

I encounter different scenarios where strings are involved. The goal is to extract the text in between the || symbols. If there is only one ||, then the first part should be taken. For example: Useless information|| basic information|| advanced informa ...

sending a pair of variables via jQuery and AJAX

Having difficulty posting two variables using ajax and jquery when a button on a confirm window is pressed. Each variable can be displayed separately, but not both at the same time. UPDATE - Issue resolved. I overlooked including a necessary file. My mist ...