20- Exercize - moving an element [ Array ]

Good morning people i follow the course of mosh and i am stack in square backet.
I still found the same topic but i don’t undestand we use that “[0]” at the end of command.

I copy the code here for undestand all things!

const numbers = [1, 2, 3, 4 ];
const output = move (numbers , 1,-2);
console.log(output);

function move(array ,index , offset)
{
    const position = index + offset ;
    if( ( position >=0 ) || (array.length <0 ))
    {
        console.error('Invalid offset ');
        return;
    }
    const output = [...array];
    //const element = output.splice(index,1)[0]; // // <---- this line
    //output.splice(position,0,element);
    const element =  output.splice(index,1);
    console.log("This is element zero [0] , ", element[0]) // <---- this line
    return output;

}

Documentation of developer.mozilla.org ----> Array.prototype.splice() - JavaScript | MDN

I don not found the square bracket in documentation or video.
Can you explain why we need that parameter?
If i change that parameter doesn works.

zero maybe it’s refer to the first element array but which one?

I am confusing.

Thanks for your time and help me!

Hi,
I am not a JS big dev but some methods return an array. So does splice(). So you can access an index by simply providing it within square brackets. At least that was my assumption. because it doesn’t seem to work.

So basically this splice() method allows to insert/remove/replace elements in an array.
But it also extract an array of elements it did process in the same time.

I did just try a few things to demonstrate its behaviour.

const numbers = [1, 2, 3, 4 ];
let index = 1;
let deleteNumber = 1;

console.log("nb: " + numbers);

const element =  numbers.splice(index, deleteNumber);

console.log("elt: " + element);

console.log("nb: " + numbers);

Output

"nb: 1,2,3,4"
"elt: 2"
"nb: 1,3,4"

Changing a bit

const numbers = [1, 2, 3, 4, 5, 6, 7 ];
let index = 2;
let deleteNumber = 3;

console.log("nb: " + numbers);

const element =  numbers.splice(index,deleteNumber);

console.log("elt: " + element);

console.log("nb: " + numbers);

Output

"nb: 1,2,3,4,5,6,7"
"elt: 3,4,5"
"nb: 1,2,6,7"

So here indeed we spliced from index 2 a set of 3 elements
Index 2 is indeed 3 and 3 element are 3,4,5.

Inserting elements

const numbers = [1, 2, 6, 7 ];
let index = 2;
let deleteNumber = 0;

const nbToInsert = [3, 4, 5 ]

console.log("nb: " + numbers);

const element =  numbers.splice(index,deleteNumber,nbToInsert);

console.log("elt: " + element);

console.log("nb: " + numbers);

Output

"nb: 1,2,6,7"
"elt: "
"nb: 1,2,3,4,5,6,7"

Hypothesis is potentially wrong :clown_face:

I may miss something about JS but the assumption is wrong. It returns undefined when you use square brackets. At least when the deleteNumber parameter is 0. In such cas there is no array returned.

let numbers = [1, 2, 6, 7 ]; // Changed to let because I thought maybe const is causing the problem I met but no.
let index = 2;
let deleteNumber = 0;

const nbToInsert = [3, 4, 5 ]

console.log("nb: " + numbers);

const element =  numbers.splice(index,deleteNumber, nbToInsert);

console.log("elt: " + element);

console.log("nb2 : " + numbers);

const x = numbers.splice(2, 3); // Not behaving as demonstrated before... Why ?
console.log("nb: " + numbers + ", x: "+ x + ", indexed output: " + x[0]); // OMG !

Output

"nb: 1,2,6,7"
"elt: " // We did not delete any element so it is not returned by splice
"nb2 : 1,2,3,4,5,6,7"
"nb: 1,2, x: 3,4,5,6,7, indexed output: 3,4,5"

The value x did not return the same as before. Not working as I did expect from eariler test.

Instead it did remove all the rest of the collection.
Also the index did return more than an integer. It did actually return the part that I was expecting to be removed.

splice seems to output a collection of collection

Adding those extra lines

console.log("x[0]:" + x[0]);
console.log("x[1]:" + x[1]);
console.log("x[2]:" + x[2]);
console.log("x[3]:" + x[3]);

Output

"x[0]:3,4,5"
"x[1]:6"
"x[2]:7"
"x[3]:undefined"

Just a note. It seems it divised the rest of the array to a set of elements. and index 0 is actually what I was hoping to work with.

It works with other languages

My assumption came from the fact I use C# on regular basis. And then it works as I assumed

using System;
using System.Text;


	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Hello World");

			int[] consecutiveNumbers =  new int[] {1,2,3,4,5};

			Display(consecutiveNumbers);
			
			int[] test = Extract(consecutiveNumbers,1,3);
			
			Display(test);
			
			Console.WriteLine(Extract(consecutiveNumbers,1,3)[1]);
		}
		
		static void Display<T>(T[] array){
			StringBuilder sb = new StringBuilder();
			foreach(T item in array){
				sb.AppendLine(item.ToString());
			}
			
			Console.WriteLine(sb.ToString());
		}
		
		static T[] Extract<T>(T[] array, int startIndex, int numberOfItemsToExtract){
			
			// No time to do the check logic but it would be here
			// We assume we are not a muppet and know how to use the function flawlessly
			
			T[] x = new T[0];
			
			for (int i = 0; i < numberOfItemsToExtract; i++)
			{
				Array.Resize(ref x, x.Length+1);
				x[i] = array[startIndex + i];
			}
			
			return x;
		}
	}

Output

Hello World
1
2
3
4
5

2
3
4

3

I 1st display the whole collection

Then something I extract
Then and index on the same method and it works like a charm.

Hope you get a proper answer.

Cheers.

1 Like

splice return an array so putting [0] return the first item of this array.
If you are deleting more than one, it would only show the first one only. The lesson is about moving an element not more than one therefore you could use [0].
element =[2]
element[0]=2

when you change the parameter, it didn’t work because there is only 1 delete item in the array. if you delete 2, you can use [1]. Mosh seems to be just showing a shortcut. Hope this clear up your confusing.