JavaScript Reverse array with with splice() method reverse array with recursion,reverse array with pointers,reverse array

I'm following a course of learning Javascript, saw this code but don't know exactly how it works. Basically what it does is reverse the numbers in the array.

Anyone who has a deeper understanding and would like to explain me of what the code does exactly?

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var knop = document.getElementById("knop");
knop.addEventListener("click", reverse);

function reverse() {
  for (var i = 0, j = a.length; i < a.length; i++) {
    a.splice(i, 0, a[j - 1]);
    a.splice(j, 1);
  }
  document.getElementById("demo1").innerHTML = a;
}
   <p id="demo1">Hier komt de inhoud na het omkeren</p>
    <button type="button" id="knop">Keerom</button>
Answer:1

I'm assuming you're speaking of this part specifically (not the dom interaction)

the simplest way to see it is to add a console.log()

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (var i = 0, j = a.length; i < a.length; i++) {
  a.splice(i, 0, a[j - 1]);
  console.log('index:',  i)
  console.log('copy:',  a.join(','))
  a.splice(j, 1);
  console.log('trim:',  a.join(','))
}
Answer:2

First, lets read what Array.splice() does:

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements.

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

  • start: Index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end of the array (with origin -1, meaning -n is the index of the nth last element and is therefore equivalent to the index of array.length - n) and will be set to 0 if absolute value is greater than the length of the array.
  • deleteCount (Optional): An integer indicating the number of old array elements to remove. If deleteCount is omitted, or if its value is equal to or larger than array.length - start (that is, if it is equal to or greater than the number of elements left in the array, starting at start), then all of the elements from start through the end of the array will be deleted. If deleteCount is 0 or negative, no elements are removed. In this case, you should specify at least one new element (see below).
  • item1, item2, ... (Optional): The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.

You should first note that splice() mutates the original array. So, on every iretarion of the loop, basically you are performing these actions:

a.splice(i, 0, a[j - 1]);

Add the last element of the current array at the position i.

a.splice(j, 1);

Remove the last element on the array.

This will be easy to check if we add some logs:

var a = [1, 2, 3, 4, 5];

var knop = document.getElementById("knop");
knop.addEventListener("click", reverse);

function reverse()
{
  for (var i = 0, j = a.length; i < a.length; i++)
  {
    console.log("-----------------");
    console.log("Iteration: " + i);
    console.log("-----------------");
    console.log(`array before insert at position ${i}: ${a}`);
    a.splice(i, 0, a[j - 1]);
    console.log(`array after insert at position ${i}: ${a}`);
    a.splice(j, 1);
    console.log(`array after delete last element: ${a}`);
  }
  document.getElementById("demo1").innerHTML = a;
}
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
<p id="demo1">Hier komt de inhoud na het omkeren</p>
<button type="button" id="knop">Keerom</button>
Answer:3
knop.addEventListener("click", reverse); //attaches the eventListener to the variable `knop` so when the it will clicked it will trigger `reverse` event.

//This creates a loop which runs through whole array.
for (var i = 0, j = a.length; i < a.length; i++) {
    a.splice(i, 0, a[j - 1]);
    a.splice(j, 1);
  }

This add a new item at index i. And the new item added is the last item of the array

a.splice(i, 0, a[j - 1]);

This line removes the last item of the array which is added at index i.

a.splice(j, 1);

Below is example how array changes

[1,2,3,4,5,6] => [6,1,2,3,4,5] => [6,5,1,2,3,4] => [6,5,4,1,2,3] => [6,5,4,3,1,2] => [6,5,4,3,2,1](completely reversed)

The code start removing elements from last and adding them to their position which should be in reversed array. For example:

  • last will be moved to 1st place
  • Second last will be moved to second place
  • Second to second last place
  • First will be moved to last place
Answer:4

See this array.splice and then come back here.

Now that you know what array.splice() does.

Here basically two things are happening:

1. a.splice(i, 0, a[j - 1]);

This part of code takes the current last element of a(a[j - 1]) and puts it at the ith index of a

and shifts the elements to the right of ith index by one position.

EXAMPLE-1 in first step:

i = 0

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

j = a.length

a[j - 1] = 10

result of a.splice(i, 0, a[j - 1]); is

a = [10,1,2,3,4,5,6,7,8,9,10]

2. a.splice(j, 1);

In this step we remove extra last element left in a after Step-1

From EXAMPLE-1 we see that length of a has increased by 1 unit.

So in this step we take the last element of a(now a[j]) and remove it.

to get resultant a = [10,1,2,3,4,5,6,7,8,9]

Now for i = 1

a.splice(i, 0, a[j - 1]); gives a = [10,9,1,2,3,4,5,6,7,8,9] and

a.splice(j,1); gives a = [10,9,1,2,3,4,5,6,7,8]

This process is repeated till i == a.length i.e no more elements left to rotate.

Answer:5

Let's assume that we have the following .filter function: search(searchQuery: string) { let results = myArray.filter(item => item.title.toLowerCase().includes(searchQuery) || item....

Let's assume that we have the following .filter function: search(searchQuery: string) { let results = myArray.filter(item => item.title.toLowerCase().includes(searchQuery) || item....

  1. filter function with multiple criteria
  2. filter function with lambda python
  3. filter function with multiple criteria in r
  4. filter function with lambda
  5. filter function with
  6. filter function with sql
  7. filter function with angularjs
  8. filter with function javascript
  9. filter with function python
  10. filter with function excel
  11. filter with function java
  12. filter function in r
  13. filter function in google sheets
  14. filter function in power bi
  15. filter function in matlab
  16. filter function in js
  17. filter function in excel 2016
  18. filter function in dax
  19. filter function in jquery
  20. filter function in powerapps

My task was to create a while loop that counts the number of letter characters in a sentence written by the User. This function would only count the number of letter characters, no special characters. ...

My task was to create a while loop that counts the number of letter characters in a sentence written by the User. This function would only count the number of letter characters, no special characters. ...

  1. javascript character letter
  2. javascript check character letter
  3. javascript regex first character letter

So I'm basically making a grid where a single click is a circle and a double click is a square. However, if I go back to an already clicked box and make a single or double click, it changes the shape ...

So I'm basically making a grid where a single click is a circle and a double click is a square. However, if I go back to an already clicked box and make a single or double click, it changes the shape ...

How to sort the array of json data having letters and digits? JS: function sortOn(property) { return function (a, b) { if (a[property] < b[property]) { return -...

How to sort the array of json data having letters and digits? JS: function sortOn(property) { return function (a, b) { if (a[property] < b[property]) { return -...