I need to get all the words from a sentence and also their index position within the sentence. The same word can happen multiple times in the sentence.
I was trying to do this using the filter method but the index indicates the position in the array not the position within the sentence.
var sentence = "This is a short sentence, a demo sentence."
sentence.split(" ").filter((word, index) => {
}
You can use .reduce:
const sentence = "This is a short sentence, a demo sentence.";
let index = 0;
const nonAlphabeticWithoutSpace = /[^a-zA-Z ]/g;
const res = sentence.split(" ").reduce((acc, item) => {
// get word without other characters
const word = item.replace(nonAlphabeticWithoutSpace, "");
// get prev indices of this word
const wordIndices = acc[word];
// create/update the indices list
acc[word] = wordIndices ? [...wordIndices, index] : [index];
// increment the index
const nonAlphabetic = item.match(nonAlphabeticWithoutSpace);
index += nonAlphabetic
? word.length+nonAlphabetic.length+1
: word.length+1;
return acc;
}, {});
console.log(res);
If you want to disregard case senstivity, use .toLowerCase().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With