DEV Community

SCDan0624
SCDan0624

Posted on

Intro to data structures part 1 Arrays

Intro

Data can be stored and accessed in many different ways in Javascript. In part one we will look how to store, access, and manipulate data in arrays.

How to Store Data

To store data in a non nested array the following syntax is used:

let myArray = ["basketball", 1, true ]
console.log(myArray.length); // 3
Enter fullscreen mode Exit fullscreen mode

As you can see an array can store multiple data types such as strings, booleans, and numbers. Using .length you can also see how many items are in the array.

A more complex array is a nested array where the array contains another array or an object:

let myArray = [
  [1,2,3],[4,5],"test"
]

Enter fullscreen mode Exit fullscreen mode

How to Access Array Data

In an array each array item has an index. The index acts as the position of the item of the array. Every array index starts at zero and is increased by one. To access the array item we use console.log, followed by the array variable name, followed by a bracket with the index inside:

let myArray = ["Robert","Tom","Megan"];

console.log(myArray[0]) // Robert
console.log(myArray[1]) // Tom
console.log(myArray[2]) // Megan
Enter fullscreen mode Exit fullscreen mode

You can also set an item in an array using bracket notation:

let myArray = ["Robert","Tom","Megan"];

myArray[1] = "Tommy"

console.log(myArray) // [ 'Robert', 'Tommy', 'Megan' ]
Enter fullscreen mode Exit fullscreen mode

Add Items to an Array with push() and unshift()

Array.push() and Array.unshift() are methods used to quickly add items to an array. Array.push() adds to the end of an array while Array.unshift() adds to the beginning of an array:

let myArray = ["Robert","Tom","Megan"];


myArray.push("Bobby")
myArray.unshift("Dwight")

console.log(myArray) // [ 'Dwight', 'Robert', 'Tom', 'Megan', 'Bobby' ]
Enter fullscreen mode Exit fullscreen mode

Remove Items from an Array using pop() and shift()

If you would like to remove items from the end of an array use the Array.pop() method, while using the Array.shift() method to remove items from the beginning of an array:

let myArray = ["Robert","Tom","Megan"];

myArray.pop() // "Megan"

console.log(myArray) // [ 'Robert', 'Tom' ]

myArray.shift() // "Robert"

console.log(myArray) // [ 'Tom' ]
Enter fullscreen mode Exit fullscreen mode

Conclusion

You are now set to create, access, and modify arrays. In part 2 we will look at more complex array manipulation, including how to copy arrays.

Top comments (0)