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

164
Visualizações
Merging Nested Arrays from Reduce Method

Prompt: Create a function prioritize that accepts an array and a callback. The callback will return either true or false. prioritize will iterate through the array and perform the callback on each element, and return a new array, where all the elements that yielded a return value of true come first in the array, and the rest of the elements come second.

CODE:

function prioritize(array, callback) {
  return array.reduce((accum, item) => {
    if (callback(item)) {
        accum[0].push(item)
      } else {
        accum[1].push(item)
      }
    return accum;
  }, [[], []])
}

// Uncomment these to check your work!
                 
function startsWithS(str) { return str[0].toLowerCase() === 's'; } //boolean, should be true or false
                 
const tvShows = ['curb', 'rickandmorty', 'seinfeld', 'sunny', 'friends'] // array
                 
console.log(prioritize(tvShows, startsWithS)); // should log: ['seinfeld', 'sunny', 'curb', 'rickandmorty', 'friends']

I am having trouble figuring out how to merge the nested array that 'accum' returns to have the output return ['seinfeld', 'sunny', 'curb', 'rickandmorty', 'friends']. Any tips on how to go about solving this?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You just have to flatten the returned result:

function prioritize(array, callback) {
    return array.reduce((accum, item) => {
      if (callback(item)) {
          accum[0].push(item)
        } else {
          accum[1].push(item)
        }
      return accum;
    }, [[], []]).flat();
  }
  
  // Uncomment these to check your work!
                   
  function startsWithS(str) { return str[0].toLowerCase() === 's'; } //boolean, should be true or false
                   
  const tvShows = ['curb', 'rickandmorty', 'seinfeld', 'sunny', 'friends'] // array
                   
  console.log(prioritize(tvShows, startsWithS)); // should log: ['seinfeld', 'sunny', 'curb', 'rickandmorty', 'friends']

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