Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
91 views
in Technique[技术] by (71.8m points)

javascript - return array of phrases by substracting each string from the previous one

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In this case, it is best to use a regular expression. Since part of your expression is dynamically generated, you need to build one using the RegExp object:

const sentences = [
  { reference: "Beautiful" },
  { reference: "Is beautiful" },
  { reference: "This is beautiful and This forest is beautiful" },
];

function getSentences() {
  const result = [];

  for (let i = sentences.length - 1; i >= 0; --i) {
    if (i - 1 >= 0) {
      var regexp = new RegExp(sentences[i - 1].reference + "$", "ig");
      const res = sentences[i].reference.replace(regexp, '');
      result.push(res);
    } else {
      result.push(sentences[i].reference);
    }
  }
  return result;
}

console.log(getSentences());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...