Skip to content

Instantly share code, notes, and snippets.

@SanjeQi
Last active August 8, 2022 16:10
Show Gist options
  • Save SanjeQi/028f94e701a7c1962d42a77b1f3a3ce0 to your computer and use it in GitHub Desktop.
Save SanjeQi/028f94e701a7c1962d42a77b1f3a3ce0 to your computer and use it in GitHub Desktop.
Methods on arrays info. Important !!!
const alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
// => undefined
alphabet.length;
// => 26
alphabet[alphabet.length - 1];
// => "z"
------------------------------------------
.push() and .unshift()
#With the .push() method, we can add elements to the end of an Array:
const superheroes = ['Catwoman', 'She-Hulk', 'Jessica Jones'];
superheroes.push('Wonder Woman');
// => 4
superheroes;
// => ["Catwoman", "She-Hulk", "Jessica Jones", "Wonder Woman"]
#We can also .unshift() elements onto the beginning of an Array:
const cities = ['New York', 'San Francisco'];
cities.unshift('Los Angeles');
// => 3
cities;
// => ["Los Angeles", "New York", "San Francisco"]
#Notice that the value returned by both methods is the length of the updated Array.
#Destructive vs. Nondestructive
#Both .push() and .unshift() update or mutate the original Array, adding elements directly to it.
#Operations that modify the #original collection are destructive, and
#those that leave the original collection intact are nondestructive.
----------------------------------------------------
#Mutating the original Array isn't necessarily a bad thing, but there's also a way to add
#elements nondestructively, leaving #the original Array intact.
#Spread Operator
#ES2015 introduced the spread operator, which looks like an ellipsis: .... The spread operator
#allows us to spread out the #contents of an existing Array into a new Array, adding new elements but preserving the original:
const coolCities = ['New York', 'San Francisco'];
const allCities = ['Los Angeles', ...coolCities];
coolCities;
// => ["New York", "San Francisco"]
allCities;
// => ["Los Angeles", "New York", "San Francisco"]
#We created a new Array instead of modifying the original one — our coolCities Array was untouched.
#We can also use the #spread operator to add a new item to the end of an Array without modifying the original:
const coolCats = ['Hobbes', 'Felix', 'Tom'];
const allCats = [...coolCats, 'Garfield'];
coolCats;
// => ["Hobbes", "Felix", "Tom"]
allCats;
// => ["Hobbes", "Felix", "Tom", "Garfield"]
-----------------------------------------------------------
Remove Elements from an Array
#As complements for .push() and .unshift(), respectively, we have .pop() and .shift().
.pop() and .shift()
#The .pop() method removes the last element in an Array, destructively updating the original Array:
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
days.pop();
// => "Sun"
days;
// => ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
#The .shift() method removes the first element in an Array, also mutating the original:
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
days.shift();
// => "Mon"
days;
// => [Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
-------------------------------------------------------------------
.slice()
#To remove elements from an Array nondestructively (without manipulating the original Array), we can
#use the .slice() #method. Just as the name implies, the .slice() method returns a portion, or slice, of an Array.
With No Arguments
#If we dont provide any arguments, .slice() will return a copy of the original Array with all elements intact:
const primes = [2, 3, 5, 7];
const copyOfPrimes = primes.slice();
primes;
// => [2, 3, 5, 7]
copyOfPrimes;
// => [2, 3, 5, 7]
#Note that the Array returned by .slice() has the same elements as the original, but its
#a copy — the two Arrays point to #different objects in memory. If you add an element to one of
#the Arrays, it does not get added to the other:
const primes = [2, 3, 5, 7];
const copyOfPrimes = primes.slice();
primes.push(11);
// => 5
primes;
// => [2, 3, 5, 7, 11]
copyOfPrimes;
// => [2, 3, 5, 7]
With Arguments
#We can provide two arguments to .slice(), the index where the slice should
#begin and the index before which it should end:
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
days.slice(2, 5);
// => ["Wed", "Thu", "Fri"]
#If no second argument is provided, the slice will run from the index specified
#by the first argument to the end of the Array:
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
days.slice(5);
// => ["Sat", "Sun"]
#To remove the first element and return a new Array, we call .slice(1):
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
days.slice(1);
// => ["Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
#And we can remove the last element in a way that will look familiar from earlier in this lesson:
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
days.slice(0, days.length - 1)
// => ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
// remove the last element the easy way
days.slice(0,-1)
// => ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
#In fact, .slice() provides an easier syntax for grabbing the last element in an Array:
days.slice(-1);
// => ["Sun"]
days.slice(-3);
// => ["Fri", "Sat", "Sun"]
#When we provide a negative index, the JavaScript engine knows to start counting from the
#last element in the Array instead #of the first.
----------------------------------------------------------------
.splice()
#While .slice() allows us to return a piece of an Array without mutating
#the original (nondestructive), .splice() performs #destructive actions.
#The documentation shows three ways to use .splice():
array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, item1, item2, ...)
-------
With a Single Argument
array.splice(start)
#The first argument expected by .splice() is the index at which to begin the splice.
#If we only provide the one argument, .splice() will destructively remove a chunk
#of the original Array beginning at the provided index and continuing to the end of the Array:
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
days.splice(2);
// => ["Wed", "Thu", "Fri", "Sat", "Sun"]
days;
// => ["Mon", "Tue"]
#Notice that .splice() returns the removed chunk and leaves the remaining elements in the original Array.
#With a negative 'start' index, the opposite happens:
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
// => ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
days.splice(-2);
// => ["Sat", "Sun"]
days;
// => ["Mon", "Tue", "Wed", "Thu", "Fri"]
-------
With Two Arguments
#array.splice(start, deleteCount)
#When we provide two arguments to .splice(), the first is still the index at
#which to begin splicing, and the second dictates how many elements we want to
#remove from the Array. For example, to remove 3 elements, starting with the element at index 2:
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
// => ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
days.splice(2, 3);
// => ["Wed", "Thu", "Fri"]
days;
// => ["Mon", "Tue", "Sat", "Sun"]
-----------------------------------------------------------------
Replace Elements in an Array
.splice() with 3+ arguments
array.splice(start, deleteCount, item1, item2, ...)
#After the first two, every additional argument passed to .splice() will be inserted
#into the Array at the position indicated by the first argument. We can replace a single
#element in an Array as follows, discarding a card and drawing a new one:
const cards = ['Ace of Spades', 'Jack of Clubs', 'Nine of Clubs', 'Nine of Diamonds', 'Three of Hearts'];
cards.splice(2, 1, 'Ace of Clubs');
// => ["Nine of Clubs"]
cards;
// => ["Ace of Spades", "Jack of Clubs", "Ace of Clubs", "Nine of Diamonds", "Three of Hearts"]
#Or we can remove two elements and insert three new ones as our restaurant expands its vegetarian options:
const menu = ['Jalapeno Poppers', 'Cheeseburger', 'Fish and Chips', 'French Fries', 'Onion Rings'];
menu.splice(1, 2, 'Veggie Burger', 'House Salad', 'Teriyaki Tofu');
// => ["Cheeseburger", "Fish and Chips"]
menu;
// => ["Jalapeno Poppers", "Veggie Burger", "House Salad", "Teriyaki Tofu", "French Fries", "Onion Rings"]
#We aren t required to remove anything with .splice() — we can use it to insert
#elements anywhere within an Array. Here #we are adding new books to our library in alphabetical order:
const books = ['Bleak House', 'David Copperfield', 'Our Mutual Friend'];
books.splice(2, 0, 'Great Expectations', 'Oliver Twist');
// => []
books;
// => ["Bleak House", "David Copperfield", "Great Expectations", "Oliver Twist", "Our Mutual Friend"]
#Notice that .splice() returns an empty Array when we provide a second argument of 0.
#This makes sense because the return #value is the set of elements that were removed, and we are telling
#it to remove 0 elements.
-----------------------------------------------------------------------------------------------------------
Using the Computed Member Access Operator to Replace Elements
#If we only need to replace a single element in an Array, there is a simpler solution than .splice():
const cards = ['Ace of Spades', 'Jack of Clubs', 'Nine of Clubs', 'Nine of Diamonds', 'Three of Hearts'];
cards[2] = 'Ace of Clubs';
// => "Ace of Clubs"
cards;
// => ["Ace of Spades", "Jack of Clubs", "Ace of Clubs", "Nine of Diamonds", "Three of Hearts"]
#However, using the computed member access operator ([]) is still destructive — it modifies the original Array.
#There is a #nondestructive way to replace or add items at arbitrary points within an Array, and
#it involves two of the concepts we #learned earlier.
----------------------------------------------------------------------------------------------------
Slicing and Spreading
#Combining .slice() and the spread operator allows us to replace elements nondestructively, leaving
#the original Array #unharmed:
const menu = ['Jalapeno Poppers', 'Cheeseburger', 'Fish and Chips', 'French Fries', 'Onion Rings'];
const newMenu = [...menu.slice(0, 1), 'Veggie Burger', 'House Salad', 'Teriyaki Tofu', ...menu.slice(3)];
menu;
// => ["Jalapeno Poppers", "Cheeseburger", "Fish and Chips", "French Fries", "Onion Rings"]
newMenu;
// => ["Jalapeno Poppers", "Veggie Burger", "House Salad", "Teriyaki Tofu", "French Fries", "Onion Rings"]
---------------------------------------------------------------------------------------------------------------------
Identify Nested Arrays
#In the above slicing and spreading example, if we dont use the spread operator we are left with
#an interesting result:
const menu = ['Jalapeno Poppers', 'Cheeseburger', 'Fish and Chips', 'French Fries', 'Onion Rings'];
const newMenu = [menu.slice(0, 1), 'Veggie Burger', 'House Salad', 'Teriyaki Tofu', menu.slice(3)];
newMenu;
// => [["Jalapeno Poppers"], "Veggie Burger", "House Salad", "Teriyaki Tofu", ["French Fries", "Onion Rings"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment