Friday 21 August 2020

JavaScript array operations, the hard way (Part 1/2)

Back when I was a JavaScript novice (which, believe it or not, wasn't all that long ago), I often struggled with arrays. I knew perfectly well what arrays were; I just had trouble making them do exactly what I wanted.

For instance, sometimes I wanted to add an element in the middle of an array, or remove an element. And I had to jump through all sorts of hoops to achieve the desired results. It was hours of intensive concentration, catering for edge cases and generally tearing my hair out. But guess what - I eventually succeeded.

So imagine my consternation when I found out that all I was trying to achieve, could have been easily accomplished using the splice() method. (Here's a description of that method, if you're so inclined.)

Still, let's not let my youthful folly go to waste. Today, let's walk through how I managed to write functions to add and delete from arrays. For that, I'll be using an array of snake names...

Ssssay what?


Why snakes?!

Hey, don't diss snakes. Snakes are cool, yo. Also kind of creepy, but mostly cool.

Adding elements

What I was trying to do was add a single element into an array. So if I created this array...
var snakes = ["cobra", "viper", "adder", "python", "aconada"];


...and ran this function, addToArray(), passing in snakes, "mamba" as the element and 2 as the position I wanted to slot it in...
var snakes = ["cobra", "viper", "adder", "python", "aconada"];

function addToArray(arr, elem, pos)
{
    //TBA
}

snakes = addToArray(snakes, "mamba", 2)


...I would get this.
["cobra", "viper", "mamba", "adder", "python", "aconada"]


Yes yes, I know now that all I really had to do was this.
var snakes = ["cobra", "viper", "adder", "python", "aconada"];

snakes.splice(2, 0, "mamba");


But me being young and stupid, I naturally had to do it the hard way. Let's see what I did. First, I declared an array, temp, set the value to arr, and returned it.
function addToArray(arr, elem, pos)
{
    var temp = arr;

    return temp;
}


I checked if the length of arr was 0. If so, I set the first element of arr to elem, and that was it.
function addToArray(arr, elem, pos)
{
    var temp = arr;

    if (arr.length == 0)
    {
        temp[0] = elem;
    }

    return temp;
}


The key thing was the Else block. I had to ensure that all the other elements at the position pos and after, got shifted one position upwards. To do this, I used a For loop, iterating through the end position of arr plus one (because we'd be creating one extra slot), until pos.
function addToArray(arr, elem, pos)
{
    var temp = arr;

    if (arr.length == 0)
    {
        temp[0] = elem;
    }
    else
    {
        for(var i = arr.length; i > pos; i--)
        {

        }
    }

    return temp;
}


And then "shift" the values.
function addToArray(arr, elem, pos)
{
    var temp = arr;

    if (arr.length == 0)
    {
        temp[0] = elem;
    }
    else
    {
        for(var i = temp.length; i > pos; i--)
        {
            temp[i] = temp[i - 1];
        }
    }

    return temp;
}


Using snakes, and 2 as pos, I would get this so far.
["cobra", "viper", "adder", "adder", "python", "aconada"]


And of course, the coup de grace...
function addToArray(arr, elem, pos)
{
    var temp = arr;

    if (arr.length == 0)
    {
        temp[0] = elem;
    }
    else
    {
        for(var i = temp.length; i > pos; i--)
        {
            temp[i] = temp[i - 1];
        }

        temp[pos] = elem;
    }

    return temp;
}


And that would be it. This would work for all cases where the position to be added were in the middle of the array.
["cobra", "viper", "mamba", "adder", "python", "aconada"]


But what if I wanted to append the new element to the end? This would be the easy way.
snakes.push("mamba");


But no, again, I had to do it the hard way. This would require another If-Else block.
function addToArray(arr, elem, pos)
{
    var temp = arr;

    if (arr.length == 0)
    {
        temp[0] = elem;
    }
    else
    {
        if (pos >= arr.length)
        {

        }
        else
        {
            for(var i = temp.length; i > pos; i--)
            {
                temp[i] = temp[i - 1];
            }

            temp[pos] = elem;       
        }
    }

    return temp;
}


And set the last element of temp, plus one, to elem.
function addToArray(arr, elem, pos)
{
    var temp = arr;

    if (arr.length == 0)
    {
        temp[0] = elem;
    }
    else
    {
        if (pos >= arr.length)
        {
            temp[arr.length] = elem;
        }
        else
        {
            for(var i = temp.length; i > pos; i--)
            {
                temp[i] = temp[i - 1];
            }

            temp[pos] = elem;       
        }
    }

    return temp;
}


So if I did this...
var snakes = ["cobra", "viper", "adder", "python", "aconada"];

snakes = addToArray(snakes, "mamba", snakes.length);


... I would get this.
["cobra", "viper", "adder", "python", "aconada", "mamba"]


This was relatively straightforward, though. The nightmare was just beginning!

Next

Removing elements the hard way.

No comments:

Post a Comment