Search code examples
javascriptarraysjsoninverted-index

JavaScript: How to rebuild text from an inverted index?


I have an inverted index in the following format:

{
 IndexLength: 5,
 InvertedIndex: {
  word1: [0, 2, 4],
  word2: [1, 3]
 }
}

What is the most efficient way of transforming this into "word1 word2 word1 word2 word1" string using JavaScript?


Solution

  • You can use two forEach() loops to create array and then use join() to get string.

    var obj = {IndexLength: 5,InvertedIndex: {word1: [0, 2, 4],word2: [1, 3]}}
    
    var arr = []
    Object.keys(obj.InvertedIndex).forEach(k => obj.InvertedIndex[k].forEach(a => arr[a] = k))
    console.log(arr.join(' '))