0

I have a Javascript array.

var myarray = ["100", "200", "", ""];

I am trying to change all blank values in the array to Number.NaN.

I can find examples online to change falsey values to 0, but I am not sure how to do it the other way around?

3
  • Empty strings are not null. I suggest you edit your title, it's misleading and incorrect. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Sep 26, 2020 at 16:06
  • Thanks for the feedback. I have update the title Commented Sep 26, 2020 at 16:13
  • do you have only strings in the array? Commented Sep 26, 2020 at 16:15

3 Answers 3

1

Try using map function

const newArray=myarray.map(no=>{return parseInt(no)})
Sign up to request clarification or add additional context in comments.

3 Comments

This doesn't work, the values in the array still show as "100", "200", "", ""
@user3580480" He gave an incomplete example and no explanation. What map does is it creates a new array based on the values of the original, and returns that array. So you need to assign its result to a variable. const newArray = myarray.map(...)
1

By having only strings, you could map with a default value.

var array = ["100", "200", "", ""];

array = array.map(v => v || NaN);

console.log(array);

Comments

0

To change all the empty strings in your existing array in place to NaN, you can loop over the elements of the array:

var myarray = ["100", "200", "", ""];

for (let i = 0; i < myarray.length; i++){
  if (myarray[i] === "") {
    myarray[i] = NaN;
  }
}

console.log(myarray);

To return a new array with the empty strings replaced by NaN, you can use Array.map:

var myarray = ["100", "200", "", ""];

const newArray = myarray.map(el => el === "" ? NaN : el);

console.log(newArray);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Comments

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.