0

I am working on a project that is using the google cloud speech-to-text api. The result from the api returns an object that has multiple arrays of transcript and each array contains an array for each word and their properties, which is an object. I want to filter through every words in the transcript, and see if it matches another array of words I want to filter out.

Here's a simplified example if it sounds confusing.

resultFromApi = {
   results:[
      [{word:"hello", startTime:"00:00:00",endTime:"00:00:02"},...],
      [{word:"world", startTime:"00:00:02",endTime:"00:00:04"},...]
   ]
}
wordsToFilter = ["hello", "there", "this", "is", "a", "test"]

My question is, is there a faster way other than something like this?

resultFromApi.results.forEach((result) => {
   result.forEach((e) => {
      if(wordsToFilter.includes(e.word)){
         ...
      }
   })
});

Edit: Syntax problem

1
  • Yes, I edited it. Sorry for the inconvenience. Commented Nov 29, 2019 at 7:43

1 Answer 1

2

At the minimum, one thing you can do to improve the computational complexity of the code would be to change the wordsToFilter array to a Set. The complexity of Array.prototype.includes is O(n), but the complexity of Set.prototype.has is O(1). So if

if(wordsToFilter.includes(e.word)){

is your current code, and it works for you, you can change the code to

const wordsToFilter = new Set(["hello", "there", "this", "is", "a", "test"]);
// ...
if(wordsToFilter.has(e.word)){

to decrease the computational complexity by a factor of n, from O(n^3) overall to O(n^2).

You have an array of arrays of objects, and you need to iterate over all objects, so you have to use a nested loop to iterate, which is O(n ^ 2), so after that, there's no way to fundamentally improve the computational complexity.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for answering, I will take a look into Set, and how it achieves O(1) when searching.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.