JavaScript: get words and its indices in a sentence

Viewed 331

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) => {
    
}
3 Answers

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().

Use map instead of filter, loop the array and find position by calculating the letter count.

...and also their index position within the sentence.

By index I assume the position at which the word starts in the sentence.

var sentence = "This is a short sentence, a demo sentence."
let position = 0;
// the words array
const wordsList = sentence.split(" ");

// get the word and position in sentence
const wordDetails = wordsList.map((word, index) => {
  // +1 to account for space
  position = index && wordsList[index - 1].length + position + 1;
  return {
    word,
    position
  };
});

console.log(wordDetails);

If you need a different output like { <word> : [pos1, pos2] } try below sample

var sentence = "This is a short sentence, a demo sentence."
let position = 0;
// the words array
const wordsList = sentence.split(" ");
let wordDetails = {};

// get the word and position in sentence
wordsList.forEach((word, index) => {
  // +1 to account for space
  position = index && wordsList[index - 1].length + position + 1;

  // check if entry exists
  if (!wordDetails[word]) {
    wordDetails[word] = [];
  }

  // insert the position in array
  wordDetails[word].push(position)
});

console.log(wordDetails);

  // below code will execute an object with key of
  // the index and value 
  
  const sentence = "This is a short sentence, a demo sentence."
        let result = {}
        sentence.split(" ").forEach((word, index) => {
            result = {
                ...result,
                [index]: word
            }
        })
        console.log(result)
        /*
        the result will be like below:
        {
            0: "This"
            2: "a"
            1: "is"
            4: "sentence,"
            3: "short"
            6: "demo"
            5: "a"
            7: "sentence."
        }
        */

Related