JS Array
Download (.odt) Download (Markdown)let array = [1, 2, 3, 4, 5, “Hello World”, true, undefined];
Get items of array
[hook]Return an item by index (starting from 0):
// array = [1, 2, 3, 4, 5, "Hello World", true, undefined];
console.log(array[0]); // prints 1 to the console
console.log(array[1]); // prints 2 to the console
Return index of an item (first occurrence) using indexOf(item) method (returns -1 if item is not found):
// array = [1, 2, 3, 4, 5, "Hello World", true, undefined];
console.log(array.indexOf("Hello World")); // prints 5 to the console because the item "Hello World" is found on index 5
Return the length of array using the length property (counts from 1):
// array = [1, 2, 3, 4, 5, "Hello World", true, undefined];
console.log(array.length); // array contains 8 items so it prints 8 to the console
Check if an item is in the array
[hook]Using includes(item) method:
// array = [1, 2, 3, 4, 5, "Hello World", true, undefined];
console.log(array.includes("Hello World")); // prints true to the console
Using includes(item) method with two arguments (second is starting index):
// array = [1, 2, 3, 4, 5, "Hello World", true, undefined];
console.log(array.includes("Hello World", 6)); // prints false to the console because it starts looking for "Hello World" from 7th element (true)
Modify an item
[hook]Modify an item on a specific index (indexes start from 0):
// array = [1, 2, 3, 4, 5, "Hello World", true, undefined];
array[6] = false; // the 7th item of array changes from true to false: [1, 2, 3, 4, 5, "Hello World", false, undefined]
Add items to the start or end of array
[hook]Add items to the start of array using unshift(item1, item2) method (can have limitless number of parameters):
// array = [1, 2, 3, 4, 5, "Hello World", false, undefined];
array.unshift("boiii", "gurl"); // array will contain the following items: ["boiii", "gurl", 1, 2, 3, 4, 5, "Hello World", false, undefined]
Add items to the end of array using push(item1, item2) method (can have limitless number of parameters):
// array = ["boiii", "gurl", 1, 2, 3, 4, 5, "Hello World", false, undefined];
array.push(NaN, null, "Bye World"); // array will contain the following items: ["boiii", "gurl", 1, 2, 3, 4, 5, "Hello World", false, undefined, NaN, null, "Bye World"]
Remove a single item from the start or end of array
[hook]Remove first item of array using shift() method (also returns the removed item):
// array = ["boiii", "gurl", 1, 2, 3, 4, 5, "Hello World", false, undefined, NaN, null, "Bye World"];
let removedFromStart = array.shift(); // removedFromStart stores the item "boiii" which is removed from array. Array will contain the following items: ["gurl", 1, 2, 3, 4, 5, "Hello World", false, undefined, NaN, null, "Bye World"]
Remove last item of array using pop() method (also returns the removed item):
// array = ["gurl", 1, 2, 3, 4, 5, "Hello World", false, undefined, NaN, null, "Bye World"];
let removedFromEnd = array.pop(); // removedFromEnd stores the item "Bye World" which is removed from array. Array will contain the following items: ["gurl", 1, 2, 3, 4, 5, "Hello World", false, undefined, NaN, null]
Add or remove multiple items anywhere inside array
[hook]Remove items using splice(startingIndex, numberOfItemsToRemove) method (creates and returns a new array with removed items):
// array = ["gurl", 1, 2, 3, 4, 5, "Hello World", false, undefined, NaN, null];
let removedFromMiddle = array.splice(7, 4); // Removes 4 items starting from index 7 and stores them in removedFromMiddle: [false, undefined, NaN, null]. The original array will contain the following items: ["gurl", 1, 2, 3, 4, 5, "Hello World"]
Remove and add items at the same time using splice(startingIndex, numberOfItemsToRemove. itemToAdd1, itemToAdd2) method (there can be limitless number of itemToAdd parameters, creates and returns a new array with removed items):
// array = ["gurl", 1, 2, 3, 4, 5, "Hello World"];
let removedFromMiddle2 = array.splice(1, 5, 21, 69); // removes 5 items starting from index 1 and stores them in removedFromMiddle2: [1, 2, 3, 4, 5]. Then it adds the items 21 and 69 to the original array, also starting from index 1. The original array will contain the following items: ["gurl", 21, 69, "Hello World"]
(if you just want to add items without removing any, provide 0 to the second, numberOfItemsToRemove parameter)
Add items of array to another array
[hook]Spread operator:
// array = ["gurl", 21, 69, "Hello World"];
let array2 = ["Goodbye World", "See ya"];
array.push(...array2); // adds items of array2 to the end of array so array will contain the following items: ["gurl", 21, 69, "Hello World", "Goodbye World", "See ya"]
Iterate through the array
[hook]Iterate through the array using for loop:
// length starts from 1 and index from 0!
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
// prints the item in index i of array during each iteration
Using forEach(function(item){}) method:
array.forEach(function(item) {
console.log(item);
});
// item parameter gets the value of next item during each iteration
// shorthand:
array.forEach(item => console.log(item));
Warning!
If you use return inside the callback function provided as a paramater to forEach then return only quits the callback function.
E.g.
function containsHelloWorld(array) {
array.forEach(function(item) {
if (item === "Hello World") {
return true;
}
});
return false;
}
The containsHelloWorld(array) function will always return false because if it finds the string "Hello World" it returns with true value from the callback function then it returns with false value from the containsHelloWorld(array) function (which is probably not what you want if you write this piece of code).
In this case it's better to use a for loop:
function containsHelloWorld(array) {
for (let i = 0; i < array.length; i++) {
if (array[i] === "Hello World") {
return true;
}
}
return false;
}
This code will always return the correct value because when it finds the string "Hello World" it returns with true value from the whole containsHelloWorld(array) function so it doesn't reach the second return.
Create a new array with modified version of items from original array using map(function(item){}) method:
// array = ["gurl", 21, 69, "Hello World", "Goodbye World", "See ya"];
let newArray = array.map(item => item + 1); // Adds 1 to each items of array and adds them to newArray. The original array remains untouched. Items of array: ["gurl", 21, 69, "Hello World", "Goodbye World", "See ya"] Items of newArray: ["gurl1", 22, 70, "Hello World1", "Goodbye World1", "See ya1"]
Check a statement against all items of array using every(function(item){}) method (returns true if all items match the statement, otherwise it returns false):
// array = ["gurl", 21, 69, "Hello World", "Goodbye World", "See ya"];
let allItemsAreNumbers = array.every(item => typeof item === "number"); // allItemsAreNumbers will be false because there are also some string items in array
Ordering items using sort() method (modifies original array)
[hook]Put string items into alphabetical order - case-sensitive:
let stringArray = ["Hello", "gurl", "boiii", "World"];
stringArray.sort(); // Result: ["Hello", "World", "boiii", "gurl"]. Uppercase comes first.
Put string items into reverse alphabetical order - case-sensitive:
// stringArray = ["Hello", "World", "boiii", "gurl"];
stringArray.sort().reverse(); // Result: ["gurl", "boii", "World", "Hello"]
Put string items into alphabetical order - case-insensitive:
// stringArray = ["gurl", "boii", "World", "Hello"];
stringArray.sort(function (a, b) {
return a.toLowerCase()
.localeCompare(b.toLowerCase());
});
// Result: ["boiii", "gurl", "Hello", "World"]
Put string items into reverse alphabetical order - case-insensitive:
// stringArray = ["boiii", "gurl", "Hello", "World"];
stringArray.sort(function (a, b) {
return a.toLowerCase()
.localeCompare(b.toLowerCase());
}).reverse();
// Result: ["World", "Hello", "gurl", "boiii"]
Put number items into ascending order:
let numberArray = [69, 18, 21, 180];
numberArray.sort((a, b) => a - b); // Result: [18, 21, 69, 180] (If you call sort() on numberArray without the (a, b) => a - b callback function it checks each digit of numbers separately so the result would be: [18, 180, 21, 69])
Put number items into descending order:
// numberArray = [18, 21, 69, 180];
numberArray.sort((a, b) => b - a); // Result: [180, 69, 21, 18]
Multidimensional array
[hook]let mdArray = [["Hello", "World"], ["Pretty", "Gurl", 69]];
Return and modify items of embedded arrays:
// mdArray = [["Hello", "World"], ["Pretty", "Gurl", 69]];
console.log(mdArray[1][2]); // Prints the index 2 item - 69 - of index 1 embedded array - ["Pretty", "Gurl", 69] - to the console
mdArray[0][0] = "Goodbye"; // Result: [["Goodbye", "World"], ["Pretty", "Gurl", 69]];
Use array methods:
// mdArray = [["Goodbye", "World"], ["Pretty", "Gurl", 69]];
mdArray[0].unshift("Oh");
mdArray[1].push(21);
let removed = mdArray[1].shift();
mdArray.push(["Let's", "Go"]);
// Result: [["Oh", "Goodbye", "World"], ["Gurl", 69, 21], ["Let's", "Go"]]
Iteration:
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array[i].length; j++) {
console.log(array[i][j]);
}
} // during each iteration of inner for loop it prints the index j item of index i embedded array to the console
// or
array.forEach(function(nestedArray) {
nestedArray.forEach(function(item) {
console.log(item);
});
});