Array Basics Flashcards

1
Q

Adding to arrays

A

One way is by setting a value at a new index in the array.

var arr = [1,2,3];
arr[3] = 4;
arr; // [1,2,3,4]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Adding to arrays

Push

A

If you want to add to the end of an array, a better approach is to use the push function - this function returns the new length (the number of elements) of the array.

var arr = [3, 2, 5];
arr.push(7); // returns the new length, i.e. 4
arr; // [3, 2, 5, 7]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

add to the beginning of an array

A

you can use the unshift function. As with push, unshift returns the length of the modified array.

var arr = [1,2,3];
arr.unshift(0); // returns the new length, i.e. 4
arr; // [0,1,2,3]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Removing from arrays

A

One (not common) way to remove elements is to manually set the length of the array to a number smaller than its current length. For example:

var arr = [1,2,3];
arr.length = 2; // returns the new length
arr; // [1,2]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

pop()

A

his function works in sort of the opposite way as push, by removing items one by one from the back of the array. Unlike push, however, pop doesn’t return the length of the new array; instead, it returns the value that was just removed.

var arr = [1,2,3];
arr.pop(); // returns 3
arr; // [1,2]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

shift()

A

If you want to remove an element from the front of an array, you should shift() (like unshift, but the opposite)! As with pop(), shift() returns the removed value.

var arr = [1,2,3];
arr.shift(); // returns 1
arr; // [2,3]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

splice()

A

One of the more powerful array methods is splice, which allows you to either add to an array or remove elements or even do both! You can think of splice as a powerful generalization of push, pop, unshift, and shift all in one!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

splice()

A

The splice method accepts at least two arguments. The first argument is the starting index, indicating where values will be removed or added. The second parameter is the number of values to remove. Optionally, you can pass in an unlimited number of additional arguments; these correspond to values you’d like to add to the array. The splice method always returns an array of the removed elements. Here are some examples:

var arr = [1,2,3,4];
arr.splice(0,1); // returns [1]
arr; // [2,3,4]
var arr = [1,2,3,4];
arr.splice(0,1,5); // returns [1]
arr; // [5,2,3,4]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly