Reputation: 155
Follow the example:
const arrayOfSentences = ['fallen little short', 'hold the nominal office of governess', 'shadow of authority', 'the real evils indeed']
const arrayOfwords = ['who', 'had','fallen', 'little','short','of','a','mother','in','affection','hold','the','nominal','office','of','governess','the','mildness','of','her','temper','had','hardly','allowed','her','to','impose','any','restraint;','and','the','shadow','of','authority','being','now','long','passed','away,','they','had']
the output should be the array of words but with the sentences merged, for example ("fallen", "little", "short" -> "fallen little short"):
const mergedArray = ['who', 'had','fallen little short','of','a','mother','in','affection','hold the nominal office of
governess','the','mildness','of','her','temper','had','hardly','allowed','her','to','impose','any','restraint;','and','the','shadow of authority','being','now','long','passed','away,','they','had']
Upvotes: 0
Views: 271
Reputation: 20734
Here's a sneaky way to do that:
const arrayOfSentences = ['fallen little short', 'hold the nominal office of governess', 'shadow of authority', 'the real evils indeed']
const arrayOfwords = ['who', 'had','fallen', 'little','short','of','a','mother','in','affection','hold','the','nominal','office','of','governess','the','mildness','of','her','temper','had','hardly','allowed','her','to','impose','any','restraint;','and','the','shadow','of','authority','being','now','long','passed','away,','they','had']
let sentence = arrayOfwords.join(' ');
arrayOfSentences.forEach(s => {
sentence = sentence.replace(s, s.replace(/\s/g, '|'));
});
const mergedArray = sentence.split(' ').map(s => s.replace(/\|/g, ' '));
console.log(mergedArray);
Basically what it does is to make the whole arrayOfwords
a sentence.
Then loop through the arrayOfSentences
to find the appearances in that sentence and replace them to some placeholders.
Then re-split the sentence to an array, and replace the placeholders as what it was in arrayOfSentences
.
Upvotes: 3