Samantha J T Star
Samantha J T Star

Reputation: 32758

How can I push a null value into the start of an array?

I have this code that fetches data and puts it into an array:

    this.$httpGetTest(this.test.testId)
        .success(function (data: ITestQuestion[]) {
            self.test.qs = data; 
        });

It works and populates the array starting with self.test.qs[0].

However many times my code references this array (which contains a list of questions 1...x)

I must always remember to subract 1 from the question number and so my code does not look clear. Is there a way that I could place an entry ahead of all the others in the array so that:

self.test.qs[0] is null
self.test.qs[1] references the first real data for question number 1.

Ideally I would like to do this by putting something after the self.test.qs = and before data.

Upvotes: 0

Views: 8873

Answers (4)

Jack Culhane
Jack Culhane

Reputation: 781

You could do something like:

x = [null].concat([1, 2, 3]);

Though there isn't anything wrong with doing something like:

x[index-1]

I'd prefer it to be honest, otherwise someone might assume that the index value returned is 0 based.

Upvotes: 0

Mithun Satheesh
Mithun Satheesh

Reputation: 27845

Push values at start of array via unshift

self.test.qs.unshift(null); 

Upvotes: 1

Lucas Penney
Lucas Penney

Reputation: 2674

You can start off with an array with a null value in it, then concat the questions array to it.

var arr = [null];
arr = arr.concat(data);

Upvotes: 0

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28528

You need to use Splice(), It works like:

The splice() method changes the content of an array, adding new elements while removing old elements.

so try:

self.test.qs.splice(0, 0, null);

Here mid argument 0 is to set no elements to remove from array so it will insert null at zero and move all other elements.

Here is demo:

var arr = [];
arr[0] = "Hello";
arr[1] = "Friend";

alert(arr.join());
arr.splice(1,0,"my");
alert(arr.join());

Upvotes: 1

Related Questions