JavsScipt Array Continuation

Kinanee Samson - Dec 13 '20 - - Dev Community

This lesson is in continuation of a previous lesson, If you missed the first part of the lesson you could read it here.
In our previous post we saw what arrays are and how JavaScript implemented arrays. We looked at what an index is and how we can use it to set and retrieve values from an array, we saw that arrays have a property called length that is used to track the number of items inside of an array. We also saw how to add objects to the start of an array and to the end of an array.

Although we only worked with arrays containing strings and numbers, we can also have an array of arrays or an array of objects, lets look at a few examples of both instances.

// creating an array of arrays
var myArray = [
    [1, 3, 5, 7, 9],
    [2, 4, 6, 8, 10],
    [2, 4, 16, 256]
]

console.log(myArray)
// prints out [
    // [1,3,5,7,9],
    // [2,4,6,8,10],
    // [2,4,16,256]
// ]
console.log(myArray.length)
// prints out 3
Enter fullscreen mode Exit fullscreen mode

We can see that the array we created above is an array of arrays where each item wasn an array.. The methods we talked about in the previous lesson still applies to this lesson too. We can also have an array of objects too. lets see some examples


var myObjectArray = [
    { name : 'John Wick', movie: 'John Wick'},
    { name : 'Klaus Michaelson', movie: 'The Originals'},
    { name : 'Tommy Eagan', movie: 'Power'},
    { name: 'Vin Disel', movie: 'Fast and Furious'}
]

console.log(myObjectArray)
// prints out [
    // { name: 'John Wick', movie: 'John Wick'},
    // { name: 'Klaus Michaelson', movie: 'The Originals'},
    // { name: 'Tommy Eagan', movie: 'Power'}
    // { name: 'Vin Disel', movie: 'Fast and Furious'}
// ]
Enter fullscreen mode Exit fullscreen mode

Associative arrays?

JavaScipt does not allow associative arrays, that is an array where the index are strings, they must always be a number based index system.. if a named identifier is used to set a value on a array, that value is added to the array's object property not the list of items that the array contains. Remeber we said that arrays have a proto property of Object. The value that has a named identifier is not added to the list of items inside the array, it will not update or affect the lenght of the array and we can demonstrate this.

var animals = ['bison', 'goat', 'sheep', 'cow']
console.log(animals) 
// prints our ['bison', 'goat', 'sheep', 'cow']
animals['Reptile'] = 'Lizards'
console.log(animals)
// prints out ['bison', 'goat', 'sheep', 'cow', Reptile : 'Lizards']
console.log(animals.lenght)
// prints out 4
// and we only put 4 items in the array 

// If we use indexOf to find lizards we get -1
console.log(animals.indexOf('Liazrds'))
// prints out - 1
console.log(animals.indexOf('Reptile'))
// prints out -1
console.log(animals.Reptile)
// prints out Lizards
Enter fullscreen mode Exit fullscreen mode

Spreading an array

If you've used ES6 you won't have trouble with the spread operator or you might have, the spread operator caused me a few headaches when i was introduced to it but it shouldn't cause you headaches. The spread operator is simply a way to convert an array into a list of items and the items are arranged in the other they were in the array.. The syntax is simple; it is just three dots '...' followed by the array name. Lets see an example of the spread operator in action.

var players = ['Arnold', 'Robertson', 'Alisson', 'Fabinho']
console.log(...players)
// prints out - Arnold Robertson Alisson Fabinho
Enter fullscreen mode Exit fullscreen mode

From the example above we can see that what is being logged to the console is a list of strings instead of an array. You might be wondering how does it help us but wait what if you want to create an object and the constructor takes a lot of arguments? what if you were writing a function and you cant be sure of the amount of number of arguments that might be supplied to the function? What if you wanted to destructure an array? This is were the spread operator shines. Lets dig into a few example

// Using spread operator to pass an list of arguments to a constructor
// we might have a simple class named Person
class Person{
    name;
    job;
    age;
    sex
    // constructor accepts name, job, age, sex
    constructor(name, job, age, sex){
        this.name = name;
        this.job = job;
        this.age = age;
        this.sex = sex
    }

    // logs the persons details to the console
    showBio(){
        console.log(`Name - ${this.name}\nJob - ${this.job}\nAge - ${this.age}\nSex - ${this.sex}`)
    }
}

// This array holds the properties of the person
var personDetails = ['John Doe', 'Coder', 25, 'Male']

// we use the spread operator 
// to pass a list of items 
// in the personDetails array
// to the new person we are creating
var johnDoe = new Person(...personDetails)

// we called the show bio method
// to log the person's details to the console
johnDoe.showBio()
// logs the following to the console
// Name - John Doe
// Job - Coder
// Age - 25
// Sex - Male
Enter fullscreen mode Exit fullscreen mode

This is just one instance of using the spread operator, we can also use it to destructure an array. the next example demonstrates that

// We have our array of the persons details
var personDetails = ['John Doe', 'Coder', 25, 'Male']

// a function that destructures 
// the array we pass to it and 
// outputs the person's details

function showList(array){
    let [name, job, age, sex, club]  = [...array]
    console.log(name, job, age, sex, club)
}

showList(personDetails)
// logs out
// John Doe Coder 25 Male undefined
// Why we are getting undefined
// is becuase the array we passed
// only contains 4 items instead of 5
// so the club variable is undefined

Enter fullscreen mode Exit fullscreen mode

The spread operator also allows us to pass the items as arguments to functions that accepts arrays as arguments
like console.log or array.prototype.push.

var myArray = [1,3,4,5]
console.log(...myArray)
// logs out 1 3 4 5

let evenNumbers = [2, 4, 6, 8, 10];
myArray.push(...evenNumbers);
console.log(myArray)
// logs out [
//   1, 3, 4,  5, 2,
//   4, 6, 8, 10
// ]

Enter fullscreen mode Exit fullscreen mode

NOTE Any method that accepts arrays as arguments also accepts spread operator

Last Words

In our next article we are going to look at more functions that exists on arrays and we see how we can remove things from an array without using the index.. stay tuned and hit the follow button. And dont forget to like and comment if you found this useful

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .