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');
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,.
Share Improve this question edited Dec 9, 2017 at 4:06 dippas 60.6k15 gold badges123 silver badges132 bronze badges asked Dec 9, 2017 at 3:53 itsolidudeitsolidude 1,2793 gold badges12 silver badges25 bronze badges 01 Answer
Reset to default 4The .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 atstartingIndex
In your case:
get
is at index5
get
,easily
,the
,first
,time
is5
Strings consecutively- only want one replacement: the String
know
So you would say .splice(5, 5, "know")
Can also refer to MDN here. Cheers!