1

How can we set empty strings inside an array to null in JavaScript?

My array:

var myarray = [["01.01.2013","a"],["01.02.2013","b"],["01.03.2013",""]]

I need to replace the second value in the third element to null.

My attempt was to check whether a string is empty and then set it to null but that results in "null" and not null.

6
  • Out of curiosity... why? Besides that, how are you outputting the result? Commented Apr 2, 2014 at 17:46
  • 2
    Show your attempt so that we can explain what you did wrong. Commented Apr 2, 2014 at 17:47
  • I plot the result. I need the null in order to detect missing points and break the graph for them (jqplot). Commented Apr 2, 2014 at 17:47
  • I tried myarray[2][1] = myarray.replace('', null); Commented Apr 2, 2014 at 17:49
  • 1
    that surprises me that you would get a "null" result from that since an Array doesn't have a .replace() method. Commented Apr 2, 2014 at 17:52

3 Answers 3

2

One possible approach:

myarray = myarray.map(function(el) {
  return el.map(function(v) {
    return v === '' ? null : v;
  });
});

... but I'd rather do it with a simple check, without generating tons of new arrays.

myarray.forEach(function(arr) {
  if (arr[0] === '') arr[0] = null;
  if (arr[1] === '') arr[1] = null;
});
Sign up to request clarification or add additional context in comments.

Comments

1

In ES6 (currently negligible browser support):

myarray = myarray.map(i => i.map(i => i==='' ? null : i))

IN ES5:

myarray = myarray.map(function(i){
    return i.map(function(i){
        return i==='' ? null : i;
    })
})

Comments

1

If you are just trying to detect empty strings, you don't need to set anything to null since code inside if ("") does not execute. Just check like this: if (string) { /* string is not empty */ }.

Otherwise, if you really need the element to be null, what's wrong with just assigning it? For example:

> myarray[2][1] = null;
> console.log(myarray[2]);
["01.03.2013", null] 

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.