Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

172
Vistas
How to improve time complexity of this snippet?

I am trying to improve the time complexity and quality of the code snippet below. I am iterating through one array to check if the element this array exists in the object, should this be true it should return the name matching the element id in the object. how can I do this without having a nested loop? Can someone tell me what I can do to make this algo better, please?

Thank you all in advance.

let genres = [28, 12, 878];
data = {
  genres: [
    {
      id: 28,
      name: 'Action',
    },
    {
      id: 12,
      name: 'Adventure',
    },
    {
      id: 16,
      name: 'Animation',
    },
    {
      id: 35,
      name: 'Comedy',
    },
    {
      id: 80,
      name: 'Crime',
    },
    {
      id: 99,
      name: 'Documentary',
    },
    {
      id: 18,
      name: 'Drama',
    },
    {
      id: 10751,
      name: 'Family',
    },
    {
      id: 14,
      name: 'Fantasy',
    },
    {
      id: 36,
      name: 'History',
    },
    {
      id: 27,
      name: 'Horror',
    },
    {
      id: 10402,
      name: 'Music',
    },
    {
      id: 9648,
      name: 'Mystery',
    },
    {
      id: 10749,
      name: 'Romance',
    },
    {
      id: 878,
      name: 'Science Fiction',
    },
    {
      id: 10770,
      name: 'TV Movie',
    },
    {
      id: 53,
      name: 'Thriller',
    },
    {
      id: 10752,
      name: 'War',
    },
    {
      id: 37,
      name: 'Western',
    },
  ],
};

const getGenreName = () => {
  let result = [];
  for (let genre of data.genres) {
    //console.log("genre", genre.name)
    for (let id of genres) {
      //console.log('id',genres[i])
      if (id === genre.id) result.push(genre.name);
    }
  }
  console.log(result);
};

getGenreName();
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can use reduce and includes as others have already shown. This will make the code a bit cleaner, but not change the overall runtime complexity. To improve runtime complexity you may need to use a different data structure.

For instance instead of

let genres = [1,2,3,4];

as a simple array, you could use a Set, which has a better lookup performance.

let genres = new Set([1,2,3,4]);

Then you can use this as follows

let result = data.genres
 .filter(g => genres.has(g.id))
 .map(g => g.name);

and won't need any explict for loops

about 4 years ago · Juan Pablo Isaza Denunciar

0

The simplest improvement would probably be converting genres to a Set https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set and use the has method to check if each id in the data is a member of the set of chosen genres.

You can also convert the data to a map with the ids as the keys in order to look up by id quickly instead of looping, but that is only faster if the data is reused many times.

about 4 years ago · Juan Pablo Isaza Denunciar

0

JavaScript #reduce in the example outlined below would have O(n) time complexity. This only loops through the array once. We could use filter, and map but it would result in us having to loop through the array twice.

const getGenreName = () => {
    const genreSet = new Set(genres);
    return data.genres.reduce((accumulator, { id, name }) => {
        if (genreSet.has(id)) accumulator.push(name);
        return accumulator;
    }, []);
};

console.log(getGenreName()); // [ 'Action', 'Adventure', 'Science Fiction' ]

We are initializing the reducer to start with the array [], or an empty array, and then checking to see if the genre property of the object is included in the genres array, if it isn't, return the accumulator, if it is, append it to the end of the accumulator and return it.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda