What is the best way to replace "NaN" with a blank space within an array?

How can I replace "NaN" with a space in an array?

let numbers = [1, 2, 3, NaN];
let result = numbers.map(num => isNaN(num) ? " " : num);
console.log(result);

I would like the output to be [1, 2, 3, " "]

Answer №1

One way to achieve this is by using the following code snippet:

result.map(val => isNaN(val) ? ' ' : val);

Answer №2

Check for NaN using the isNaN() method within a forEach loop.

var numbers = [1, 2, 3, NaN];
filteredNumbers = [];
numbers.forEach((num) => !isNaN(num) ? filteredNumbers.push(num) : filteredNumbers.push(''));
console.log(filteredNumbers);

Alternatively, you can achieve the same result using the map method.

var numbers = [1, 2, 3, NaN];
console.log(numbers.map((num) => isNaN(num) ? "" : num));

Answer №3

To identify elements with the value of `NaN`, you can utilize the isNaN() function.


var sampleArray = [8, NaN, 6, "NaN"];

for (var j in sampleArray)
    if (isNaN(sampleArray[j]))
        sampleArray[j] = "";

console.log(sampleArray);

Answer №4

Implement map() method:

var numbers = [9, 5, 7, 1, 'NaN']
numbers = numbers.map(num => isNaN(num)?' ':num)
console.log(numbers)

Answer №5

One option is to utilize the findIndex method. Check out the sample code below:

var data = [5, 8, 10, NaN];
var index = data.findIndex(Number.isNaN);
data[index] = "empty";
console.log(data);

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

Use JavaScript to dynamically add CSS styles to elements before and after a button wrapper

My code seems simple, but for some reason it's not working. I'm trying to add CSS styles to a button when there is a div with the class .wp-block-group both before and after the button. $(".btn-superimposed-wrapper").each(function () ...

Seeking materials for WebDriverJs?

It has come to my attention that there are some valuable resources available: http://docs.seleniumhq.org/docs/03_webdriver.jsp https://code.google.com/p/selenium/wiki/WebDriverJs However, I am curious if there exists a comprehensive website that prese ...

Triggering the body onunload event

I am currently developing a HTA that needs to make final modifications on the onunload event. However, I am facing an issue as the event does not appear to be triggered. Can someone confirm if this event is still supported? Is there an equivalent event in ...

Nightwatch execute() function not technique following anticipate

After reviewing the documentation, I am confident that this code should work correctly. However, I am encountering an issue where something needs to run once the expect has finished, but it doesn't seem to be functioning as expected. Functioning Code ...

The hidden attribute of UIWebView and its interplay with JavaScript

In the webViewDidStartLoad method, I hide the webview. Then a request is made. In the webViewDidFinishLoad method, I use stringByEvaluatingJavaScriptFromString. Finally, the webview is shown again. However, when I run the app, I can still see how the Java ...

res.send No data being transmitted - in the realm of Express.js

I'm currently developing a calculator app using Express.js, but I seem to be encountering an issue with the res.send Method as I am not getting any response. My expectation is for my webpage to display the sum from the calculator.js file. Nodemon is a ...

Add a class if the particular class is missing from the webpage

Seeking a solution in JS, I am facing a challenge in creating a series of elements with active states, each opening a caption below when clicked. Utilizing .addClass, .removeClass, and .toggleClass in combination, only one element can be active at a time. ...

Custom error messages for data types in Ajv

Recently, I delved into using Ajv with ajv-errors to validate JSON schema and generate personalized error messages. While everything is functioning correctly so far, I encountered a challenge in setting custom error messages for individual values based on ...

Display the accurate prompt in the event of 2 `catch` statements

elementX.isPresent() .then(() => { elementX.all(by.cssContainingText('option', text)).click() .catch(error => { throw {message: "Unable to select text in dropdown box"} ...

Using Chart.js to display JSON data in a graphical format

I am facing an issue and need some help. I have gone through various tutorials and questions, but none of them seem to address my specific problem. When making an ajax request to my PHP file, I receive a JSON response like this (as seen in the console log) ...

"Combining multiple attributes to target elements while excluding specific classes

My dilemma lies in the following selector that identifies all necessary elements along with an extra element containing the "formValue" class which I aim to omit $("[data-OriginalValue][data-OriginalValue!=''][data-TaskItemID]") ...

AJAX working concurrently across multiple threads

After learning that JavaScript is single-threaded (as discussed in this question: If Javascript is not multithreaded, is there any reason to implement asynchronous Ajax Queuing?), I started to explore how this concept applies to my developed application. H ...

Customizing JSON Data Structure in jQuery DataTables for Enhanced Display

Is it possible to populate a custom JSON data structure using jQuery Datatable? I have found a solution for the default Datatable JSON structure that works well, but I would like to use my own JSON structure instead. I am currently using DataTables 1.10.7. ...

Concealing a DisplayFor component with the help of Jquery

Hey there, I currently have a 'td' element that appears like this <td style="font-weight:bold"> @Html.DisplayFor(x => x.Parts[i].QtyInItem, new { htmlAttributes = new { @class = "qtyInItem" } }) </td> A ...

Replace Formik with useFormik to streamline your code

I have implemented Formik/Yup for validation on a page that triggers a GraphQL mutation. The code is functioning as expected: export default function RemoveUserPage() { const [isSubmitted, setIsSubmitted] = useState(false); const [isRemoved ,setIsRemo ...

Ways to retrieve the <select> value in AngularJS

Having trouble passing the selected value from my tab to my $scope object. Here's the snippet of my HTML code. <div ng-controller="RouteController"> <select ng-model="selector" ng-options="opt as opt.label for opt in options"> ...

Extract table information from MuiDataTable

I am having trouble retrieving the row data from MuiDataTable. When I try to set the index from the onRowSelectionChange function to a state, it causes my checkbox animation to stop working. Below is how my options are currently configured: const option ...

Difficulty integrating Bootstrap with JavaScript file in Visual Studio Code

I am attempting to incorporate a dynamic progress bar by utilizing Bootstrap's progressbar and creating a custom JavaScript file. The goal is to continuously adjust the width of the progress bar at regular intervals to give the appearance of a moving ...

Issue with publishing npm package using yarn package manager

I'm currently in the process of releasing a fresh package. Utilizing ES6, I've been transpiling my files through babel to start with. However, I've hit a roadblock at this particular stage: https://i.stack.imgur.com/iIVp6.png This part se ...

Why is Ajax/FormData rounding my decimal values?

When sending data from a form to my PHP script, I am utilizing the new FormData() method to retrieve the values. However, there are additional values that I append later on which are not part of the form: var fd = new FormData(document.getElementById(&apo ...