Home > Mobile >  Using Multiple Splice insert with javascript
Using Multiple Splice insert with javascript

Time:10-22

im having problem with multiple usage of splice() method.

string= "test"
splitted = string.split('');
splitted.splice(1,0,"ww");
console.log(splitted);

so when i use like this output is (5) ['t', 'ww', 'e', 's', 't'] so all good. but lets assume that i want to use this method multiple times with a different indexes and different string to insert. im looking for somethig like this;

string= "test"
splitted = string.split('');
splitted.splice((1,0,"ww"),(2,0,"ss"),(3,0,"dd"));
console.log(splitted);

thanks for your help

CodePudding user response:

Splice mutates the original object and returns the removed values. so calling it multiple times on the variable splitted does the trick you desire.

string= "test"
splitted = string.split('');
splitted.splice(1,0,"ww")
splitted.splice(2,0,"ss")
splitted.splice(3,0,"dd")

console.log(splitted);

CodePudding user response:

If you want to do multiple operations you have to call splice multiple times. Either you code it to be called multiple times or you use an array and loop to call it multiple times.

const string = "test"
const splitted = string.split('');

const updates = [
  [1, 0, "ww"],
  [2, 0, "ss"],
  [3, 0, "dd"]
];

updates.forEach(update => splitted.splice(...update));

console.log(splitted);

  • Related