NERDY AMIGO

documenting my programming journey here

Arrays in depth

Arrays

The JavaScript Array is a global object that is used in the construction of arrays, which are high-level, list-like object

// let's create an array
var pokemon = ["charmander", "charmeleon", "charizard"]
// we can obtain the length of our array by calling the length method on it like so:
console.log(pokemon.length) // should return 3
// the console.log statement prints the results of this statement to our console

Why are arrays useful

Unlike in other languages the length nor the types of it's elements are fixed, this means that javascript arrays are dynamic, they can shrink and expand depending on your needs. Let's say your application returned a list of urls like so:

// list of random urls
var urls = ["google.com", "news.com", "facebook.com"]

An array is a good data structure to store these array in case you need to do something with them, something that's close to a real world application would be to turn this array into a new array of anchor tags for your application, we could do this pretty easily by using map to create a new array with the changes we need without destroyig the original:

// let's create a new array, I won't be using a for loop but you can if you want
var anchors = urls.map(url => `<li class="link-item><a href=${url} class="link>${url}</a></li>`)
// this will return us a the following html: <li class="link-item"><a href="google.com">google.com</a></li>

Let's say that you only need to access the first Element in the array well you can do that as well, arrays are indexed starting at 0, so you could do something like poekemon[0] which would return back the first element of that array charmander

Array methods

Earlier we called some methods on the arrays we have created, we called length on the pokemon array and map on the urls array, these are methods that have been built into the array object, we do not have to define them, they have been defined for us, we can just invoke them by adding a dot at the end of the array name:

Length

// create a new array
var arr = [1,2,3,4]
// call the length method which returns the length of the array
arr.length // => 4

Push

Want to add something to the end of an array? Use the push method

// Create the array - we are missing charizard!!
var pokemon = ["charmander", "charmeleon"]
pokemon.push("charizard")

Pop

What about removing the last element of an array? Use pop

// let's change the last element to be something like "squirtle" then we can change it back, we'll use index positions to change the first item
pokemon[pokemon.length - 1] = "squirtle"

// now lets remove it using pop, it also gives us back what we just removed, here I stored it in a variable
var removed = pokemon.pop()

Shift

Want to remove the first element of the array and store? Use shift()

// lets create a new pokemon array with 3 new pokemon
var pokemon = ["squirtle", "wartortle", "Blastoise"]
// Now let's remove squirtle and store it in array, remeber this will remove the item so the length of thr array will also change
var squirtle = pokemon.shift()
console.log(squirtle) // => squirtle

Unshift

Want to add something to the beginning of an array? Let's use unshift

var cars = ["ford", "honda", "toyota"]
// let's add chevy to beginning using the unshift method, this method will also return you the new length of the array, since the array has been changed
cars.unshift("chevy")
console.log(cars) //=> ["chevy", "ford", "honda", "toyota"]

Concat

Want to merge two arrays together? Arrays have a method called concat when you use it you can merge the two arrays and get a new one as a result, this method does not mutate the arrays as it returns a brand new one so it can be saved in a variable for later use

var pokemon = ["charmander", "charmeleon", "charizard"]
var pokemon2 = ["squirtle", "wartortle", "Blastoise"]

var concatArray = pokemon.concat(pokemon2)
console.log(concatArray) // =>  ["charmander", "charmeleon", "charizard", "squirtle", "wartortle", "Blastoise"];

Filter

Let's say you have an array with a lot of number but you only wanted to get the numbers that are greater than 18, let's use filter, which is a method that creates a new array with all elements that pass the test implemented by the provided function.

var number = [20, 2, 3, 89, 18, 19, 5, 6,7, 3, 0]
let res = number.filter(x => x > 18);
console.log(res) // => should give us every number > 18

FIND INDEX

FROM JOB INTERVIEW

What if you have a list of items and you need to know where the first time an item is found in a list? You can use the findIndex method, which returns that items index when found and -1 if the item was not found at all in the array. I had an interview where I was asked to create a function that returns the number of times a city was repeated in an array so cities = ["nashville", "nashville", "new york", "nashville"] would return 1 since nashville is the only city being repeated in the array, here is what I came up with

This is the question I got asked during a phone screening, the thing is at the time Icouldn't come up with a solution, after some research I tried applying what I learned to this solution, which uses a forEach loop and the indexOf method, instead of two for loops, I used the forEach to loop through each city in the array, then using the index which can be acceses through the forEach params

unction countDuplicatesInList(city_list) {
  var count = 0;
  var alredySeen = []
 
  city_list.forEach((city, index) => {
    if(city_list.indexOf(city, index + 1) > -1) {
      if(seen.indexOf(city) === -1) {
        alreadySseen.push(city)
        count++
      }
    }

  })
 
  console.log(alreadySeen)
  return count;
}

CHALLENGES

USE ARRAY'S MAP AND FILTER FOR THE FOLLOWING
FROM FREECODECAMP.COM

The variable watchList holds an array of objects with information on several movies. Use a combination of filter and map to return a new array of objects with only title and rating keys, but where imdbRating is greater than or equal to 8.0. Note that the rating values are saved as strings in the object and you may want to convert them into numbers to perform mathematical operations on them.

// the global variable
var watchList = [
                 {  
                   "Title": "Inception",
                   "Year": "2010",
                   "Rated": "PG-13",
                   "Released": "16 Jul 2010",
                   "Runtime": "148 min",
                   "Genre": "Action, Adventure, Crime",
                   "Director": "Christopher Nolan",
                   "Writer": "Christopher Nolan",
                   "Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
                   "Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
                   "Language": "English, Japanese, French",
                   "Country": "USA, UK",
                   "Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
                   "Metascore": "74",
                   "imdbRating": "8.8",
                   "imdbVotes": "1,446,708",
                   "imdbID": "tt1375666",
                   "Type": "movie",
                   "Response": "True"
                },
                {  
                   "Title": "Interstellar",
                   "Year": "2014",
                   "Rated": "PG-13",
                   "Released": "07 Nov 2014",
                   "Runtime": "169 min",
                   "Genre": "Adventure, Drama, Sci-Fi",
                   "Director": "Christopher Nolan",
                   "Writer": "Jonathan Nolan, Christopher Nolan",
                   "Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
                   "Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
                   "Language": "English",
                   "Country": "USA, UK",
                   "Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
                   "Metascore": "74",
                   "imdbRating": "8.6",
                   "imdbVotes": "910,366",
                   "imdbID": "tt0816692",
                   "Type": "movie",
                   "Response": "True"
                },
                {
                   "Title": "The Dark Knight",
                   "Year": "2008",
                   "Rated": "PG-13",
                   "Released": "18 Jul 2008",
                   "Runtime": "152 min",
                   "Genre": "Action, Adventure, Crime",
                   "Director": "Christopher Nolan",
                   "Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
                   "Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
                   "Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
                   "Language": "English, Mandarin",
                   "Country": "USA, UK",
                   "Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
                   "Metascore": "82",
                   "imdbRating": "9.0",
                   "imdbVotes": "1,652,832",
                   "imdbID": "tt0468569",
                   "Type": "movie",
                   "Response": "True"
                },
                {  
                   "Title": "Batman Begins",
                   "Year": "2005",
                   "Rated": "PG-13",
                   "Released": "15 Jun 2005",
                   "Runtime": "140 min",
                   "Genre": "Action, Adventure",
                   "Director": "Christopher Nolan",
                   "Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
                   "Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
                   "Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
                   "Language": "English, Urdu, Mandarin",
                   "Country": "USA, UK",
                   "Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
                   "Metascore": "70",
                   "imdbRating": "8.3",
                   "imdbVotes": "972,584",
                   "imdbID": "tt0372784",
                   "Type": "movie",
                   "Response": "True"
                },
                {
                   "Title": "Avatar",
                   "Year": "2009",
                   "Rated": "PG-13",
                   "Released": "18 Dec 2009",
                   "Runtime": "162 min",
                   "Genre": "Action, Adventure, Fantasy",
                   "Director": "James Cameron",
                   "Writer": "James Cameron",
                   "Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
                   "Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
                   "Language": "English, Spanish",
                   "Country": "USA, UK",
                   "Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
                   "Metascore": "83",
                   "imdbRating": "7.9",
                   "imdbVotes": "876,575",
                   "imdbID": "tt0499549",
                   "Type": "movie",
                   "Response": "True"
                }
];

// Add your code below this line

var filteredList = watchList.map(movie => {
  let result = {};
  result.title = movie.Title;
  result.rating = movie.imdbRating;
  return result;
}).filter(item => item.rating >= 8.0)


// Add your code above this line

console.log(filteredList); 
IMPLEMENT THE FILTER METHOD USING FOREACH
// the global Array
var s = [23, 65, 98, 5];

Array.prototype.myFilter = function(callback){
  var newArray = [];
  // Add your code below this line
  this.forEach(item => {
    if(callback(item) === true) {
      newArray.push(item)
    }
  })
  // Add your code above this line
  return newArray;

};

var new_s = s.myFilter(function(item){
  return item % 2 === 1;
});
NextPrevious