Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
list comprehension containing enumerate equivalent in javascript

Please what is the equivalent in javascript of this python code

guessed_index = [
        i for i, letter in enumerate(self.chosen_word)
        if letter == self.guess
    ]

Both enumerate and list comprehension are not present in the ES6 equivalent, how to I combine both ideas into one

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Perhaps findIndex is useful?

const word = "Hello";
const guess = "o";
const guessed_index = [...word].findIndex(letter => letter === guess);
console.log(guessed_index)
    

about 4 years ago · Juan Pablo Isaza Report

0

Focussing on the iterable/enumerate part of your question rather than the specific task you're performing: You can implement a JavaScript analogue of Python's enumerate using a generator function, and consume the resulting generator (which is a superset of an iterable) via for-of (or manually if you prefer):

function* enumerate(it, start = 0) {
    let index = start;
    for (const value of it) {
        yield [value, index++];
    }
}

const word = "hello";
const guess = "l";
const guessed_indexes = [];
for (const [value, index] of enumerate(word)) {
    if (value === guess) {
        guessed_indexes.push(index);
    }
}
console.log(`guessed_indexes for '${guess}' in '${word}':`, guessed_indexes);

Or you can write a specific generator function that does the task of finding matches:

function* matchingIndexes(word, guess) {
    let index = 0;
    for (const letter of word) {
        if (letter === guess) {
            yield index;
        }
        ++index;
    }
}

const word = "hello";
const guess = "l";
const guessed_indexes = [...matchingIndexes(word, guess)];

console.log(`guessed_indexes for '${guess}' in '${word}':`, guessed_indexes);

about 4 years ago · Juan Pablo Isaza Report

0

Just for clarity for potential readers that are not proficient in python, below is the python loop equivalent of your comprehension:

guessed_index = []
i = 0
for letter in self.chosen_word:
    if letter == self.guess:
        guessed_index.append(i)
    i += 1
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!