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

162
Visualizações
Javascript function to get 3 objects based by props

I am trying to make function to get top3 objects from an array based by props. My site can't load up so i think this function runs endlessly but i cant figure out why.

renderItems = (items) => {
    let top3 = []
    let tempArr = items  
    let allNumbers = []
    while (top3.length < 3){
        allNumbers = []
        for(let i = 0; i < tempArr.length; i++){
        allNumbers = [...allNumbers, tempArr[i].hearts] 
        }
        const result = tempArr.filter(i => i.hearts === Math.max(...allNumbers))
        top3 = [...top3, ...result]
        let countOfdeleted = 0
        for(let i = 0; i < result.length; i++){
            tempArr.splice(result[i].id-countOfdeleted, 1)
            countOfdeleted++
        }
        for(let i = 0; i < tempArr.length; i++){
            tempArr[i].id = i
        } 
    } 
    console.log(top3);  
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This answer is based on the assumption that 'items' is an array of objects and that each object in 'items' will have at-least 2 props namely 'id' and 'hearts'.

Further, there is no clarity on the significance of 'countOfdeleted' and 'tempArr'. Hence, it is assumed

  1. that one needs to know how many elements of the 'items' array were not included (in the top3) as 'countOfdeleted'
  2. that the remaining objects need to have their 'id' updated (based on index)

With the aforementioned assumptions, the below should implement the required logic:

const items = [
{ id: 0, hearts: 5 }, { id: 1, hearts: 4 }, { id: 2, hearts: 5 }, 
{ id: 3, hearts: 3 }, { id: 4, hearts: 5 }, { id: 5, hearts: 2 },
{ id: 6, hearts: 2 }, { id: 7, hearts: 1 }, { id: 8, hearts: 4 }
];

const getTop3 = (arr = items) => {
const maxVal = arr.reduce((fin, itm) => itm.hearts > fin ? itm.hearts : fin, 0);
const topAll = arr.filter(obj => obj.hearts === maxVal);
const sansTop3 = arr
.filter(obj => obj.hearts !== maxVal)
.map((obj, idx) => ({...obj, id: idx}));
console.log('countOfDeleted: ', arr.length - (topAll.length > 3 ? topAll.length : 3));
console.log('rest with updated-id (tempArr): ', sansTop3);
return topAll.length > 3 ? topAll.slice(0, 3) : [...topAll];
};

console.log('\ntop3:\n^^^^\n', getTop3());

Approach / Explanation

  1. Find the 'maximum-value' (maxVal) based on the prop ('hearts')
  2. Find all objects which have the props matching maxVal (stored in array 'topAll')
  3. [Optional: Gather remaining 'items' elements and update their 'id' in 'sansTop3' array, to match the 'tempArr' in the question]
  4. [Optional: Determine the number of 'items' deleted, to match countOfdeleted in the question]
  5. If more than 3 elements have props ('heart') matching 'maxVal', return only 3; otherwise, return the all top-value element/s
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