-2

I couldn't find here a solution here at Stackoverflow, in other case I am really sorry about duplicating similar problems.

Let's say, there is an string array:

let array = ["a", "b", "c", "d", "e", "f", "g"];

and some segments to be replaced:

let toBeReplaced = [

    {s: 1, e: 2, new: ["b1", "b2", "c1", "c2", "c3"]},
    {s: 3, e: 5, new: ["d1", "e1", "e2", "f1"]},
    {s: 6, e: 0, new: ["g1", "g2", "a1"]}

];

The tricky things that these segments could be like third one, starting at the end of array and having last .e index at the beginning.

The output could be ["b1", "b2", "c1", "c2", "c3", "d1", "e1", "e2", "f1", "g1", "g2", "a1"], but it's much preferably to be like ["a1", "b1", "b2", "c1", "c2", "c3", "d1", "e1", "e2", "f1", "g1", "g2"].

If the task wouldn't have segments like third one:

let toBeReplaced = [
    
    {s: 1, e: 2, new: ["b1", "b2", "c1", "c2", "c3"]},
    {s: 3, e: 5, new: ["d1", "e1", "e2", "f1"]}
    
];
toowren
  • 85
  • 7
  • How would you know where to split the array in order to get your "most preferably" output? – Ouroborus Nov 13 '22 at 10:08
  • As for the first two, I'm pretty sure it could be done with [`.splice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice). – Ouroborus Nov 13 '22 at 10:10
  • It's a crucial part of this question https://stackoverflow.com/questions/74419451/horizontal-polygon-sides-subdivision-in-javascript, so I actually need to replace certain polygon points with interpolated set. – toowren Nov 13 '22 at 16:29

1 Answers1

0

Actually, I have found a solution. At least with first output version. Yes, splice() is good, but with indexOf() method, so you don't need to reindex everything.

Still looking for second output version solution.

let array = ["a", "b", "c", "d", "e", "f", "g"];

let toBeReplaced = [

    {s: "b", len: 2, new: ["b1", "b2", "c1", "c2", "c3"]},
    {s: "d", len: 3, new: ["d1", "e1", "e2", "f1"]},
    {s: "g", len: 3, new: ["g1", "g2", "a1"]}

];

toBeReplaced.forEach((tbr_) => {

    array.splice(array.indexOf(tbr_.s), tbr_.len, ...tbr_.new);

});

console.log(array);
toowren
  • 85
  • 7