JavaScript Array
Array
are a big part of working with JavaScript
and there are many built in methods you can use to help you work with them.
Cosinder this a cheat sheet
of some useful methods you will use over and over again!
.concat()
Merge two or more arrays together into a one new array.
// Array of shoppingList
const drinks = ["Coffee", "Pineapple Juice", "Tea"];
const snacks = ["Chocolate", "Chips"];
const shoppingList = drinks.concat(snacks);
console.log(shoppingList);
// Output: ["Coffee", "Pineapple Juice", "Tea", "Chocolate", "Chips"];
// Array of numbers
const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];
const numbers = num1.concat(num2, num3);
console.log(numbers);
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
.push()
Add one or more elements to the end of an array.
const colours = ["black", "purple", "white", "blue"];
colours.push("green");
console.log(colours);
// Output: ["black", "purple", "white", "blue", "green"];
.unshift()
Add one or more elements to the beginning of an array.
const animals = ["dog", "cat", "parrot"];
animals.unshift("rabbit");
console.log(animals);
// Output: ["rabbit", "dog", "cat", "parrot"];
.pop()
Remove the last element from an array.
const colours = ["black", "purple", "white", "blue"];
colours.pop();
console.log(colours);
// Output: ["black", "purple", "white"];
.shift()
Remove the first element from an array.
const animals = ["rabbit", "dog", "cat", "parrot"];
animals.shift();
console.log(animals);
// Output: ["dog", "cat", "parrot"];
.sort()
Sort the elements of an array in place.
// Sorting an array in alphabetical order
const months = ["January", "February", "March"];
console.log(months.sort());
// Output: ["February", "January", "March"];
// Sorting an array of numbers
const numbers = [1, 30, 4, 21, 100];
console.log(numbers.sort());
// Output: [1, 100, 21, 30, 4]
.join()
Concatenate all the elements in an array into a new string
const elements = ["Fire", "Air", "Water"];
console.log(elements.join());
// Output: "Fire,Air,Water"
console.log(elements.join("-"));
// Output: "Fire-Air-Water"
.includes()
Determine whether an array includes a certain value among its entries.
const colours = ["black", "purple", "green", "pink"];
console.log(colours.includes("pink"));
//Output: true
console.log(colours.includes("red"));
//Output: false
.filter()
Create a new array with all elements that pass the test implemented by the provided function.
const words = ["test", "hello", "mail", "gift"];
const result = words.filter((word) => word.length < 5);
console.log(result);
// Output:["test", "mail", "gift"];
.forEach()
Execute a provided function once for each entry in the array.
const numbers = [5, 10, 18, 36, 72, 46];
numbers.forEach((num) => {
console.log(num + 2);
});
// Output:
// 7
// 12
// 20
// 38
// 74
// 48
Let's connect 💜
You can follow me on Twitter, Instagram & GitHub
If you like this post. Kindly support me by Buying Me a Coffee
Discussion (0)