in this example below which is the correct way to change null to Hugo
const airplaneSeats = [
['Ruth', 'Anthony', 'Stevie'],
['Amelia', 'Pedro', 'Maya'],
['Xavier', 'Ananya', 'Luis'],
['Luke', null, 'Deniz'],
['Rin', 'Sakura', 'Francisco']
]
I tried doing airplaneSeats.splice([3][1], 1, 'Hugo')
but this was wrong why? also
i got back that the answer was airplaneSeats[3][1] = 'Hugo'
which didn’t make sense because how does that delete null
3
Answers
In JavaScript, arrays are zero-indexed, which means the counting starts from 0. So, in the given array
airplaneSeats
, the element at index [3][1] is null. When you use the assignment operator (=
) to setairplaneSeats[3][1] = 'Hugo'
, you are replacing the value at that specific index fromnull
to'Hugo'
.Now, let’s break down why
airplaneSeats.splice([3][1], 1, 'Hugo')
didn’t work as expected. Thesplice()
method is used to change the contents of an array by removing or replacing existing elements and/or adding new elements in place. The syntax forsplice()
is:start
: The index at which to start changing the array.deleteCount
: The number of elements to remove.item1
,item2
, …: The elements to add to the array.In your code —
splice([3][1], 1, 'Hugo')
— you are passing the second element of the array[3]
(which isundefined
) as thestart
argument, which is not correct. Thestart
argument should be a number indicating the index at which to start modifying the array.Furthermore,
splice()
is a method meant for one-dimensional arrays, butairplaneSeats
is a two-dimensional array. So usingsplice()
in this context would not target the intended element within the nested array.Therefore, the correct way to replace
null
with'Hugo'
in this two-dimensional array is by using the assignment statement:airplaneSeats[3][1] = 'Hugo'
. This statement directly accesses the element at index [3][1] and replaces it with'Hugo'
, without deletingnull
but rather overwriting it.If you want to use the
splice
function to replace an item in a nested array, you need to use something like my code below.You can set Hugo to that location by setting the graph coordinate like so:
As for what you tried – you can’t use chained index accessing meant for graph index access
[i][j]
as a parameter for the Array prototype method splice. You must iterate over the 1st array and use splice on the sub Array using a single index as a parameter.The function
fillNull
below will iterate over thegraph
and then use common Array methods to check fornull
and fill all instances ofnull
withval
.However, if you want a more reusable function I would break out of the check after Hugo is added to the first seat.