2

I have a big array (say 500 entries) but most of the values are Null. How can i represent the array instead of having [null, null ... 3, null, null, ...]?

the array is passed to highcharts for plotting. Highcharts plots a point for every element in the array so I really don't need those nulls.

3
  • How do you want it to be represented? Commented May 29, 2012 at 21:58
  • You got nulls and you want the array not to have them, but you got to have them.I'm confused! What is it exactly that you want then?! Commented May 29, 2012 at 21:59
  • i want javascript to understand that I have a 500 entries array with lots of null but I do not want the code to show a giant block of null's Commented May 29, 2012 at 22:37

1 Answer 1

4

If you set array[200] to something, it's not like JavaScript comes along behind you and sets array[0] through array[199]. Arrays are automatically sparse.

So is the problem that if you ask for an uninitialized element, you get undefined back instead of null? Or is there some other issue?

If it's the undefined vs null thing, then just add the nulls after you initialize it, with a loop, instead of having to put them in the big literal blob:

for (var i=0; i<array.length; ++i) { 
    if (typeof(array[i]) === 'undefined') { 
        array[i] = null; 
    } 
}

If you want nulls out past what you initialized, replace array.length with whatever your maximum index needs to be (+1, or else change the < to <=).

Sign up to request clarification or add additional context in comments.

2 Comments

a potential problem with this is Highcharts understands null but (probably) not undefined. eg: data=[null, 2, null ,4, null] will give a plot of with only 2 points with a gap in the middle
sadly, highcharts seems to not work with undefineds :(. Oh well, your answer would still make lots of sense tho :)

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.