Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace multiple elements with .splice() in javascript

Tags:

javascript

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,.

like image 853
itsolidude Avatar asked Sep 17 '25 05:09

itsolidude


1 Answers

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 remove
  • numDeletions is the number of consecutive items in the array you want to remove
  • replacement1, 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 consecutively
  • only want one replacement: the String know

So you would say .splice(5, 5, "know")

Can also refer to MDN here. Cheers!

like image 194
Joseph Avatar answered Sep 19 '25 19:09

Joseph