Day 5. Arrays

On Day 5, I learned about various array methods. There are many of them, so I linked MDN documents to every title. Reading documents is always helpful for better understanding of code. Let’s begin!

header image TIL

Array

An array can store multiple values. Each value has an index, and each index has a reference in a memory address. An index starts from zero. Each value of an array can be accessed by using their indexes.

An array is a collection of a different data types. The datas are ordered and changeable(modifiable). It can store duplicate elements of different types, and it can be empty.

How to create an empty array

//using an array constructor
const arr = Array();
let arr = new Array();

//using square brackets
const arr = [];  //most recommended

How to create an array with values

const arr = [3, 25, 6.1, 70.55, 900];
console.log('Length:', arr.length);  //Length: 5

I can use length property to find the length, or a size, of an array.

  • How can I get only the words from a text
let txt =
  'I love teaching and empowering people. I teach HTML, CSS, JS, React, Python.';
let onlyWords = /\w+/g;
console.log(txt.match(onlyWords));

If I use /\w/g, every character in the text is splitted. If I want to get a word, I should add a plus sign after \w, which means ‘matching one or more characters in a row.’

Methods to manipulate array

1. Array()

An array constructor. It creates an array.

const arr = Array();  //create an empty array
const eightEmptyValues = Array(8);  //create eight empty values
console.log(eightEmptyValues);  //[empty x 8]

const alphabet = new Array('a', 'b', 'c', 'd');

2. fill

It fills the array elements with a static value.

fill(value)
fill(value, start)
fill(value, start, end)
const fourXValues = Array(4).fill('X');  //create eight element values filled with 'X'
console.log(fourXValues);  //['X','X','X','X']

3. concat

It concatenates two arrays.

const list1 = [1, 2, 3];
const list2 = [4, 5, 6];
const list3 = list1.concat(list2);
console.log(list3);  //[1, 2, 3, 4, 5, 6]

To concatenate more than two arrays, I can put another argument at concat() using comma.

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [7, 8];
const numbers = arr1.concat(arr2,arr3); 
console.log(numbers);  //(8) [1, 2, 3, 4, 5, 6, 7, 8]

4. length

It returns the size(the number of items) of an array.

const numbers = [0, 1, 2, 3, 4];
console.log(numbers.length);  //5

5. indexOf

It checks if an item exists in an array. It returns the first index of the value if the value exists, and -1 if the value doesn’t exist.

const numbers = [1, 2, 3, 4 ,5];
console.log(numbers.indexOf(0));  //-1
console.log(numbers.indexOf(3));  //2

I can use indexOf() in a conditional to check if an item exists in an array. The condition would be indexOf() === -1 or index === -1.

6. lastIndexOf

It tells the position of the last item in the array. It returns the index if the value exists, and -1 if the value doesn’t exist.

const numbers = [1, 2, 1, 3, 5, 1, 2];
console.log(numbers.lastIndexOf(1));  //5
console.log(numbers.lastIndexOf(6));  //-1

7. includes

It checks if an item exists in an array, and returns true or false.

const numbers = [2, 15, 3, 60, 9];
console.log(numbers.includes(60));  //true
console.log(numbers.includes(0));  //false

8. Array.isArray

It checks if a data type is an array, and returns true or false.

const numbers = [0, 1, 2];
console.log(Array.isArray(numbers));  //true
console.log(Array.isArray([4]));  //true
console.log(Array.isArray(new Array(3)));  //true
console.log(Array.isArray('carrot'));  //false

9. toString

It converts array to string.

const names = ['Claus', 'Vanya', 'Five', 'Luther'];
console.log(numbers.toString());  //Claus,Vanya,Five,Luther

10. join

It joins the elements of the array. The argument I pass in the join will be joined in the array and return as a string(different from concat). By default, the items are joined with comma(with no space), but I can put others that will be joined between the items.

join()
join(separator)
const names = ['Allison', 'Diego', 'Ben'];
console.log(names.join());  //Alisson,Diego,Ben
console.log(names.join(' # '));  //Allison # Diego # Ben

11. slice

It cuts out a multiple items in range and returns a portion of array. It takes two parameters: starting and ending position. The ending position is not included. If I only put one parameter, it would return array elements from that parameter through the end of an array.

slice()
slice(start)
slice(start, end)
const numbers = [1, 2, 3, 4, 5];
//copy all items
console.log(numbers.slice());
console.log(numbers.slice(0));
console.log(numbers.slice(0, numbers.length));

console.log(numbers.slice(1,4)); //[2, 3, 4](doesn't include index 4)

12. splice

It changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. (slice + replace) It takes three parameters: starting position, number of times to be removed, and items to be added.

splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2, itemN)
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.splice());  //remove all items
console.log(numbers.splice(0,1));  //remove the first item
console.log(numbers.splice(3, 2, 7, 8));  //[1, 2, 3, 7, 8]
//starting from index 3, remove 2 items and replace them with 7, 8

13. push

It adds items to the end of an existing array. It returns the new length of the array.

const arr = ['item1', 'item2'];
arr.push('newitem');  //3
console.log(arr);  //['item1', 'item2', 'newitem']

14. pop

It removes the item in the end. It returns the removed element from the array. If the array is empty, it returns undefined.

const numbers = [1, 2, 3, 4, 5];
numbers.pop();  //5
console.log(numbers);  //[1, 2, 3, 4]

15. shift

It removes item in the beginning of the array. It returns the removed element from the array. If the array is empty, it returns undefined.

16. unshift

It adds(inserts) item in the beginning of the array. It returns the new length of the array.

unshift(element0)
unshift(element0, element1)
unshift(element0, element1, /* ... ,*/ elementN)
const numbers = [1, 2, 3, 4];
numbers.unshift(0);  //5
console.log(numbers);  //1, 2, 3, 4, 5

17. sort

It arranges array elements in ascending order, and returns the sorted array. Sort takes a call back function, which I’ll learn later.

const webTechs = ['HTML', 'CSS', 'JavaScript', 'React'];
webTechs.sort();  //['CSS', 'HTML', 'JavaScript', 'React']

//I can reverse the order after sorting
webTechs.reverse();  //['React', 'JavaScript', 'HTML', 'CSS']

Array of arrays

Array can store different data types, including an array itself.

const arrayOfArray = [[1, 2, 3], [4, 5, 6]];
console.log(arrayOfArray[0]);  //[1, 2, 3]
console.log(arrayOfArray.length);  //2

Leave a comment