Day 6 of #100DaysOfCode

Day 6

Arrays are a simple way of storing a list of data under a single variable name. They are basically single objects that contain multiple values stored in a list. We can also individually access each item in the list.

Arrays are created by placing the items inside square brackets. The content inside the brackets could be numbers, strings, objects, or even another array.

const names = [“Kabelo”, “Nii”, “John”, “Tebogo”];

const numbers = [1, 2, 3, 4, 5];

const mixed = [“Lerato, 1, 2, [“Honda”, “Tesla”, “Toyota”]];

• We can find the length of an array with the arrayName.length property.

• We can access a specific value in an array by arrayName[index]. Remember that arrays start counting at zero(0)

• We can modify an array with arrayName[index] = “New Value”. This will replace the existing value of the array with your newly created value at the specified index.

• We can find the index of an item through the arrayName.inderOf(“name”) method.

• We add items to the end of an array with arrayName.push(“item”).

• We add items to the beginning of an array with arrayName.unshift(“item”).

• We delete the last item of an array with arrayName.pop().

• We delete the first item of an array with arrayName.shift().

• If we know the index of the item we want to remove, we can use the arrayName.splice(statingIndex, numberOfItemsToDelete).

• The “for…of” statement will let you access every item in an array:

const names = [“Kabelo”, “Nii”, “John”, “Tebogo”];

for (const name of names) {
    console.log(name);
}

• If we want to do things with ALL the items in an array we use the map() method. We give a map() a function and map() calls the function for each item in the array:

function double(number) {
    return number * 2;
}

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(double);

console.log(doubled);

• We can split a string into an array with the split(“character where the split should happen”) or turn an array into a string with join().

const randomString = “Lerato, Thato, John, Linda, ”;
const firstArray = myNames.split(“,”);
const newString = firstArray.join(“,”);

We can also use toString() instead of join(), but we are forced to use a comma as our separator, while join() allows us to use any separator we like.