Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
obtenga los primeros tres elementos que tengan las calificaciones más altas de la matriz

hola tengo una pregunta necesito obtener los 3 objetos que tienen la calificación más alta (por ahora tengo 3 pero no importa porque necesito agregar más) ¿cómo puedo hacerlo? Estoy tratando de usar ordenar y distribuir, pero como esa es una matriz de objetos y otra matriz (calificación), me confundo, gracias.

 const [movies, setMovies] = useState([ { movieName: "godfather", info: "the rise of corelone family all mater is respect,money,woman but the youngest son michal has a diffrent plans...", picture: "pictures/godfather.jpg", rating: [10, 5, 1], }, { movieName: "scarface", info: "the rise of tony montata the badass man of miami want to control miami and be the number 1 of the cocaine provider ...", picture: "pictures/scarface.jpg", rating: [10, 9, 2], }, { movieName: "the-dark-knight", info: "you all knew that he will come the batman! come to fight with his popular rival the joker...", picture: "pictures/the-dark-knight-poster.jpg", rating: [10, 10, 9], }, ]);
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Como esto

 const rates = movies .reduce((acc, curr) => { const sumRate = curr.rating.reduce((acc2, curr2) => acc2 + curr2, 0) const rate = sumRate / curr.rating.length acc.push({ ...curr, rate }) return acc }, []) .sort((a, b) => a.rate - b.rate) const highestRate = rates[rates.length - 1]
about 4 years ago · Juan Pablo Isaza Relatório

0

Esta es la forma más eficiente de obtener solo los primeros tres elementos mejor calificados con tiempo O(n) (sin ordenar toda la matriz). La idea aquí es que no desea ordenar toda la matriz. Solo actualice los punteros a los tres elementos más grandes.

Cuando encuentre un valor más alto para el primer elemento, simplemente asigne el valor anterior del primer elemento al segundo elemento, y el tercer elemento al segundo elemento (porque el segundo elemento se actualiza con un valor mayor y el tercer elemento puede tomar su valor anterior). valor).

 const movies = [ { movieName: "the-dark-knight", info: "you all knew that he will come the batman! come to fight with his popular rival the joker...", picture: "pictures/the-dark-knight-poster.jpg", rating: [10, 10, 9], }, { movieName: "godfather", info: "the rise of corelone family all mater is respect,money,woman but the youngest son michal has a diffrent plans...", picture: "pictures/godfather.jpg", rating: [10, 5, 1], }, { movieName: "scarface", info: "the rise of tony montata the badass man of miami want to control miami and be the number 1 of the cocaine provider ...", picture: "pictures/scarface.jpg", rating: [10, 9, 2], }, ]; let first = { rating: [Number.NEGATIVE_INFINITY] }; let second = { rating: [Number.NEGATIVE_INFINITY] }; let third = { rating: [Number.NEGATIVE_INFINITY] }; const getTotalRating = (rating) => { return rating.reduce((prev, curr) => prev + curr, 0); }; movies.forEach((currItem) => { const currItemTotalRating = getTotalRating(currItem.rating); const firstTotalRating = getTotalRating(first.rating); const secondTotalRating = getTotalRating(second.rating); const thirdTotalRating = getTotalRating(third.rating); if (currItemTotalRating > firstTotalRating) { third = second; second = first; first = currItem; } else if (currItemTotalRating > secondTotalRating) { third = second; second = currItem; } else if (currItemTotalRating > thirdTotalRating) { third = currItem; } }); console.log(first); console.log(second); console.log(third);

about 4 years ago · Juan Pablo Isaza Relatório

0

Así es como puede ordenar por calificación promedio y total utilizando el método de sort ( docs ).

Ordenar por calificación promedio

 const getAverage = (array) => { const total = array.reduce((a, b) => a + b); return total / array.length; }; setMovies(prev => ( prev.sort((a, b) => { const aRating = a.rating; const bRating = b.rating; if (getAverage(aRating) > getAverage(bRating)) return -1; if (getAverage(aRating) < getAverage(bRating)) return 1; return 0; }) ));

Ordenar por calificación total

 const getTotal = (array) => { return array.reduce((a, b) => a + b); }; setMovies(prev => ( prev.sort((a, b) => { const aRating = a.rating; const bRating = b.rating; if (getTotal(aRating) > getTotal(bRating)) return -1; if (getTotal(aRating) < getTotal(bRating)) return 1; return 0; }) ));
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda