I am pretty new to Javascript and i am doing a course on it atm. I am searching for a way to replace multiple items in an array with 1 item but i only know how to replace a single one.here is my snipped:
let secretMessage = ["Learning", "isn't", "about", "what", "you", "get", "easily", "the", "first", "time,", "it's", "about", "what", "you", "can", "figure", "out.", "-2015,", "Chris", "Pine,", "Learn", "JavaScript"];
secretMessage.pop();
secretMessage.push('to','program');
secretMessage[6] = 'right';
secretMessage.shift();
secretMessage.unshift('Programming');
and this is what i am supposed to do: Use an array method to remove the strings get, right, the, first, time,, and replace them with the single string know,.
The .splice()
method lets you replace multiple elements in an array with one, two, or however many elements you like. Just use the syntax:
.splice(startingIndex, numDeletions, replacement1, replacement2, ... )
where:
startingIndex
is the index of the array that contains the first element you want to removenumDeletions
is the number of consecutive items in the array you want to removereplacement1
, replacement2
, ...
(however many) are the elements you wish to add to the array, beginning at startingIndex
In your case:
get
is at index 5
get
, easily
, the
, first
, time
is 5
Strings consecutivelyknow
So you would say .splice(5, 5, "know")
Can also refer to MDN here. Cheers!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With