For example,
const text = "APPLE ORANGE";
const text_position = [0,4,4,7,9];
const inserted_value = ["yo","wo","go","lo","zo"];
For this example, I would like to create an array like this:
return ["yo","APPL","wo","go","E O","lo","RA","zo","NGE"];
My code:
I am trying to merge into an array from a given string by an array of string positions. There are one string and two arrays given:
const content = "0123456789TEXT";
const footnote_position = [0, 1, 2, 2, 6]; // string positions
const footnote_value = ["ZERO", "ONE", "TWO", "TWO", "SIX"]; // inserted values
But for my code and above given content, footnote_position, and footnote_value, the algorithm must output as follow:
["ZEROR","0","ONE","1","TWO","TWO","2345","SIX","67899TEXT"]
My complete code is:
const content = "0123456789TEXT";
const footnote_position = [0, 1, 2, 2, 6]; // must be sorted
const footnote_value = ["ZERO", "ONE", "TWO", "TWO", "SIX"];
const position_set = [...new Set(footnote_position)]; // must be sorted 1,2,6
const contentArray = [];
let textArray = [];
let prev = -1;
let count = footnote_position.length;
for (let index = 0; index < count + 1; index++) {
switch (index) {
case 0: // ok
var item = footnote_position[index];
if (item != 0) {
textArray.push(content.substring(0, item));
}
footnote_position.forEach((value, position) => {
if (value == item) {
textArray.push(footnote_value[position]);
}
})
prev = item;
break;
case length: // ok
textArray.push(content.substring(prev)); // <Text>
footnote_position.forEach((value, position) => {
if (value == item) textArray.push(footnote_value[position]);
})
break;
default: // not ok
var item = footnote_position[index];
textArray.push(content.substring(prev, item));
footnote_position.forEach((value, position) => {
if (value == item) textArray.push(footnote_value[position]);
})
prev = item;
break;
}
}
console.log(textArray);
Unfortunately, my output is different as follows:
["ZERO", "0", "ONE", "1", "TWO", "TWO", "", "TWO", "TWO", "2345", "SIX", "6789TEXT"]
What went wrong? Do you have any alternative different algorithm solution for this problem?
Plus, I really have no idea why case length: is working. There is no defined variable length in the code.
