JavaScript array operations, the hard way
21st
August 2020, 00:37
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...
...and ran this function, addToArray(), passing in snakes, "mamba" as the element and 2 as the position I wanted to slot it in...
...I would get this.
Yes yes, I know now that all I really had to do was this.
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.
I checked if the length of arr was 0. If so, I set the first element of arr to elem, and that was it.
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.
And then "shift" the values.
Using snakes, and 2 as pos, I would get this so far.
And of course, the coup de grace...
And that would be it. This would work for all cases where the position to be added were in the middle of the array.
But what if I wanted to append the new element to the end? This would be the easy way.
But no, again, I had to do it the hard way. This would require another If-Else block.
And set the last element of temp, plus one, to elem.
So if I did this...
... I would get this.
This was relatively straightforward, though. The nightmare was just beginning!
Adding elements to an array, even manually, wasn't all that hard in the final analysis. But deleting... now that was a whole new kettle of fish.
Making the required array element blank would be easy. But the trick here was ensuring that the total number of elements was reduced by one! I won't go through everything I tried in order to produce the delFromArray() function, but here's what I finally did.
First, I declared temp as an empty array, and returned it.
Then I checked for an edge case. If pos wasn't a valid position within the array, I simply made sure the original array was returned.
And then there was an Else block to handle the other cases. First, I declared j and set it to -1. Then I created a For loop to iterate through the contents of arr.
With each iteration, I'd increment j, then set the current element of temp pointed to by i, to the element in arr pointed to by j. The idea was to transfer all elements, except for the element to be deleted, from arr to temp.
Here, I checked if j was equal to pos after incrementing. If it was, I incremented it again. The net effect of this was that arr would skip that position in j to be transferred.
And of course, I had to cater for one more case. If j, after being incremented, inevitably arrived at an index that was not valid for arr, the transfer would not take place.
And yes, it worked!
Looks so simple now, but I had to take a while to get my head around all of it.
And while I pretty much suffered for nothing back then, here's hoping you can learn something from this, even if it's only "don't be a hardworking idiot".
Tags
See also
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)
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");
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;
}
{
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;
}
{
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;
}
{
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;
}
{
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;
}
{
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;
}
{
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;
}
{
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);
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!
Adding elements to an array, even manually, wasn't all that hard in the final analysis. But deleting... now that was a whole new kettle of fish.
Deleting elements
Again, it could have all been accomplished by use of the splice() method. Say, I wanted to delete "mamba" from the new array.
var snakes = ["cobra", "viper", "mamba", "adder", "python", "aconada"];
snakes.splice(2, 1);
snakes.splice(2, 1);
Making the required array element blank would be easy. But the trick here was ensuring that the total number of elements was reduced by one! I won't go through everything I tried in order to produce the delFromArray() function, but here's what I finally did.
var snakes = ["cobra", "viper", "mamba", "adder", "python", "aconada"];
snakes = delFromArray(snakes, 2);
function delFromArray(arr, pos)
{
}
snakes = delFromArray(snakes, 2);
function delFromArray(arr, pos)
{
}
First, I declared temp as an empty array, and returned it.
function delFromArray(arr, pos)
{
var temp = [];
return temp;
}
{
var temp = [];
return temp;
}
Then I checked for an edge case. If pos wasn't a valid position within the array, I simply made sure the original array was returned.
function delFromArray(arr, pos)
{
var temp = [];
if (pos < arr.length && pos > arr.length)
{
temp = arr;
}
return temp;
}
{
var temp = [];
if (pos < arr.length && pos > arr.length)
{
temp = arr;
}
return temp;
}
And then there was an Else block to handle the other cases. First, I declared j and set it to -1. Then I created a For loop to iterate through the contents of arr.
function delFromArray(arr, pos)
{
var temp = [];
if (pos < arr.length && pos > arr.length)
{
temp = arr;
}
else
{
var j = -1;
for (var i = 0; i < arr.length; i++)
{
}
}
return temp;
}
{
var temp = [];
if (pos < arr.length && pos > arr.length)
{
temp = arr;
}
else
{
var j = -1;
for (var i = 0; i < arr.length; i++)
{
}
}
return temp;
}
With each iteration, I'd increment j, then set the current element of temp pointed to by i, to the element in arr pointed to by j. The idea was to transfer all elements, except for the element to be deleted, from arr to temp.
function delFromArray(arr, pos)
{
var temp = [];
if (pos < arr.length && pos > arr.length)
{
temp = arr;
}
else
{
var j = -1;
for (var i = 0; i < arr.length; i++)
{
j++;
temp[i] = arr[j];
}
}
return temp;
}
{
var temp = [];
if (pos < arr.length && pos > arr.length)
{
temp = arr;
}
else
{
var j = -1;
for (var i = 0; i < arr.length; i++)
{
j++;
temp[i] = arr[j];
}
}
return temp;
}
Here, I checked if j was equal to pos after incrementing. If it was, I incremented it again. The net effect of this was that arr would skip that position in j to be transferred.
function delFromArray(arr, pos)
{
var temp = [];
if (pos < arr.length && pos > arr.length)
{
temp = arr;
}
else
{
var j = -1;
for (var i = 0; i < arr.length; i++)
{
j++;
if (i == pos)
{
j++;
}
temp[i] = arr[j];
}
}
return temp;
}
{
var temp = [];
if (pos < arr.length && pos > arr.length)
{
temp = arr;
}
else
{
var j = -1;
for (var i = 0; i < arr.length; i++)
{
j++;
if (i == pos)
{
j++;
}
temp[i] = arr[j];
}
}
return temp;
}
And of course, I had to cater for one more case. If j, after being incremented, inevitably arrived at an index that was not valid for arr, the transfer would not take place.
function delFromArray(arr, pos)
{
var temp = [];
if (pos < arr.length && pos > arr.length)
{
temp = arr;
}
else
{
var j = -1;
for (var i = 0; i < arr.length; i++)
{
j++;
if (i == pos)
{
j++;
}
if (j <= arr.length - 1)
{
temp[i] = arr[j];
}
}
}
return temp;
}
{
var temp = [];
if (pos < arr.length && pos > arr.length)
{
temp = arr;
}
else
{
var j = -1;
for (var i = 0; i < arr.length; i++)
{
j++;
if (i == pos)
{
j++;
}
if (j <= arr.length - 1)
{
temp[i] = arr[j];
}
}
}
return temp;
}
And yes, it worked!
["cobra", "viper", "adder", "python", "aconada"];
Looks so simple now, but I had to take a while to get my head around all of it.
What was the point of this, again?
Why did I write this long-rambling story about how much of a noob I was? Well, see, the point was to illustrate how even the simplest things aren't all that simple. People take it for granted today - functions to add and delete elements from arrays are ubiquitous in almost every language I've written in - JavaScript (obviously), Ruby, PHP and so on. But what goes on behind those function calls is a lot of logic.And while I pretty much suffered for nothing back then, here's hoping you can learn something from this, even if it's only "don't be a hardworking idiot".
Thanksssssss for reading!