Let's say we have an array of object like this:
const sentences = [
{ reference: "Beautiful" },
{ reference: "Is beautiful" },
{ reference: "This forest is beautiful" },
];
As you see from the first one (first object in the array) to the last one we added word or words to shape a meaningful sentence right?
Now I want to substract each string from the previous one and return an array of phrases like this:
['This forest', 'Is', 'Beautiful']
Note that we substract it like this:
third obj: "This forest is beautiful" - "Is beautiful" = 'This forest'
second obj: "Is beautiful" - "Beautiful" = 'Is'
and the last one is just returned:
first obj: 'Beautiful'
The issue is the replace method which I used in the below code dosnt care about case insensetivity and it replaces the first occurance of the phrase not the last one:
To be clear look at the code below and the desired result I explained at the end of the code:
const sentences = [
{ reference: "Beautiful" },
{ reference: "Is beautiful" },
{ reference: "This is beautiful and This forest is beautiful" },
];
console.log(getSentences());
function getSentences() {
const result = [];
for(let i = sentences.length - 1; i >= 0; --i) {
if(i - 1 >= 0) {
const res = sentences[i].reference.replace(sentences[i - 1].reference, '');
result.push(res);
} else {
result.push(sentences[i].reference);
}
}
return result;
}
// desired result of the code would be:
//["This is beautiful and This forest", "Is", "Beautiful"]
question from:
https://stackoverflow.com/questions/65892653/return-array-of-phrases-by-substracting-each-string-from-the-previous-one 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…