3.10 Array Methods
Hello
Zen and the art of Coding
Please email hello@zenandtheartofcoding.info for a password

Array Methods

📚 Table of Contents
push()
pop()
shift()
unshift()
reverse()
sort()
concat()
includes()
slice()
splice()
forEach()
map()
filter()
find()
join()
  • so, same deal as the string methods, JS comes packed with methods for working with arrays
  • some of these, like map(), are crucial when doing real frontend work to render data on a UI in React
  • I will show a lot of the array methods here but not all, there are over 30 of them so this is about half
  • as always, ask chatgpt and Google what you need or go right to the docs (opens in a new tab) to see everything

  • an array to work with:
let peanuts = ["Snoopy", "Woodstock", "Charlie Brown"];

push()

  • push() adds an element to an array
  • it tacks it on to the end of the array
  • when you push an element to an array, that element is now last
console.log(peanuts.push("Lucy")); // ["Snoopy", "Woodstock", "Charlie Brown", "Lucy"]

pop()

  • pop() is the opposite of push(), it will remove the last element of an array
console.log(peanuts.pop()); // ["Snoopy", "Woodstock"];

shift()

  • shift() removes the first element in an array
  • it shifts all elements to a lower index
console.log(peanuts.shift()); // ["Woodstock", "Charlie Brown"]

unshift()

  • unshift() adds a new element to an array (at the beginning)
  • it "unshifts" older elements 🙃
console.log(peanuts.unshift("Lucy")); // ["Lucy", "Snoopy", "Woodstock", "Charlie Brown"]

note: if the above 4 methods are confusing, don't worry about it because push() is by far the most common and useful one


reverse()

  • heres an easy one. reverse() does exactly what you think it does. it doesn't take in any parameters and works with numbers and strings
console.log(peanuts.reverse()); // ["Charlie Brown", "Woodstock", "Snoopy"]

sort()

  • sort() is awesome but does have some quirks
  • for sorting arrays of strings alphabetically, it works beautifully off the bat
console.log(peanuts.sort()); // ["Charlie Brown", "Snoopy", "Woodstock",]
  • since JS is case sensitive, sort() will sort upper and lower case separately
let peanutsUpperAndLowerCase = [
  "Snoopy",
  "Woodstock",
  "Charlie Brown",
  "snoopy",
];
 
console.log(peanutsUpperAndLowerCase.sort());
// ["Charlie Brown", "Snoopy", "Woodtock", "snoopy"]
  • notice that "snoopy" is at the end
  • sorting numbers is a little different. under the hood, sort() converts the elements to strings and then compares them. that means you can get some wacky results
let nums = [4, 2, 0, 10, 6, 9, 42];
 
console.log(nums.sort());
// [0, 10, 2, 4, 42,  6, 9]
  • to actually sort numbers in ascending or descending order you have to pass in an optional function as the parameter to sort()
  • the way to do it is to pass in a compare function with two parameters (usually a and b) representing the elements being compared as sort() goes through the array, and to return a - b for ascending order or b - a for descending order
let ascendingSorted = nums.sort((a, b) => a - b);
 
console.log(ascendingSorted);
// [0, 2, 4, 6, 9, 10, 42]
 
let descendingSorted = nums.sort((a, b) => b - a);
 
console.log(descendingSorted);
// [42, 10, 9, 6, 4, 2, 0]
  • if that isn't crystal clear, copy and paste and steal this code for now until you can run it off the top of your head

concat()

let morePeanuts = ["Spike", "Linus", "Peppermint Patty"];
 
let lotsOfPeanuts = peanuts.concat(morePeanuts);
 
console.log(lotsOfPeanuts); // ["Snoopy", "Woodstock", "Charlie Brown", "Spike", "Linus", "Peppermint Patty"]

includes()

console.log(peanuts.includes("Snoopy")); // true
console.log(peanuts.includes("Ghostface Killa")); // false

slice()

  • also same as the string slice method
  • this works exactly the same as it does on strings as it does on arrays
  • it slices out the part that you want
  • give it the starting index and then the optional ending index
console.log(peanuts.slice(1)); // ["Woodstock", "Charlie Brown"]
console.log(peanuts.slice(0, 1)); // ["Snoopy"]

splice()

  • admittedly this one can be confusing, especially because its easy to mix this up with slice(). luckily this isn't super common but its good to have in the tool belt
  • when you splice something in, you usually remove something and then add another thing. I think of how they used to edit old school reel to reel tapes
  • the first parameter defines the position where new elements should be added (spliced in) and the second parameter defines how many elements should be removed and then the rest are what you want to add in
peanuts.splice(1, 1, "Sally", "Pig-Pen");
console.log(peanuts); // ["Snoopy", "Sally", "Pig-Pen", "Charlie Brown"]
  • we are started at index 1, removing 1 element (Woodstock) and adding in Sally and Pig-Pen

forEach()

  • forEach() essentially does the same thing as a for loop, it will give you access to the individual elements in an array
  • for loops honestly offer so much more as far as flexibility, scope and even have slightly better performance but forEach() can be clean
  • the way forEach() works is, you define the value or element you want in a function as the parameter to the method
peanuts.forEach((element) => {
  console.log(element);
});
  • will give you
Snoopy
Woodstock
Charlie Brown
  • optionally, you can also pass in the index if you need that too (I would honestly just use a for loop at this point but hey everyone has their own style)
peanuts.forEach((element, index) => {
  console.log(element, index);
});
  • will give you
Snoopy 0
Woodstock 1
Charlie Brown 2

map()

  • map() will go through each element in an array and return values based on a function that you provide to each element. that function can be whatever you want/need
  • say you have a numbers array and need to double each number:
let nums = [4, 2, 0, 10, 6, 9, 42];
 
let numsDoubled = nums.map((num) => num * 2);
 
console.log(numsDoubled);
// [8, 4, 0, 20, 12, 18, 84]
  • as I mentioned in the intro to this array methods section, map() is super important for when we get to React and instead of talking about it and saying we aren't up to that yet, I want to show why to kind of cut through the gatekeeping, demystify it and get a jump on it
  • map() actually returns a new array instead of manipulating the original one. that is important and is why it is used to render data from arrays in the actual UI instead of for loops or forEach(); map() actually returns new data
  • map() plays really well with JSX which is the React's syntax for JavaScript. it also helps provide React with unique keys which are essential for manipulating the virtual DOM
  • in real life programming, it is very common to have data as an array of objects, like this:
const users = [
  { id: 1, name: "Snoopy" },
  { id: 2, name: "Woodstock" },
  { id: 3, name: "Charlie Brown" },
];
  • if we were making a UI to display all of the users in an unordered list, this is how we would do it in React
<div>
  <ul>
    {users.map((user) => (
      <li key={user.id}>{user.name}</li>
    ))}
  </ul>
</div>

filter()

  • filer() is similar to map() in that it will create a new array based on a function that you provide
  • it will filter out any element that doesn't meet your requirements
let nums = [4, 2, 0, 10, 6, 9, 42];
 
let onlyNumsLessThanTen = nums.filter((num) => num < 10);
 
console.log(onlyNumsLessThanTen);
// [ 4, 2, 0, 6, 9 ]
  • filter works by seeing if the elements in the array are truthy or falsey based on your function
  • it is pretty good for searching for specific things
let onlyNamesThatStartWithS = peanuts.filter((name) => name[0] === "S");
 
console.log(onlyNamesThatStartWithS); // ["Snoopy"]

find()

  • find() can be handy but it only finds the first thing of what you are looking for
let nums = [4, 2, 0, 10, 6, 9, 42];
 
console.log(nums.find(num) => num < 10);
// 4

join()

  • similar to how we ended the last section with turning strings into numbers and arrays, join() is how you turn arrays into strings
  • its super straight forward, you just pass in whatever you want to join the elements with
console.log(peanuts.join(", "));
// Snoopy, Woodstock, Charlie Brown
  • actually, it still works if you don't pass in anything, just might look funny
console.log(peanuts.join());
// Snoopy,Woodstock,Charlie Brown
  • these methods to go back and forth between data types are important and insanely useful, you can see why on in the next section