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

137
Visualizações
How can i improve this Javascript code that arrange the array in ordered list first and put them in an array of array with same value?

Can this code be Improved? It arrange our array into sorted list(sortedArray) first and, the finalArray takes the final result;Example finalArray = [[1,1,1,1][2,2,2]...]

let array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20]
let sortedArray = []
let finalArray = []

sortedArray = array.sort((a, b) => {
  if (a > b) return 1;
  if (a < b) return -1;
  return sortedArray.push(a - b);
});

finalArray = sortedArray.reduce((item, index) => {
  if (typeof item.last === 'undefined' || item.last !== index) {
    item.last = index;
    item.sortedArray.push([]);
  }
  item.sortedArray[item.sortedArray.length - 1].push(index);
  return item;

}, {
  sortedArray: []
}).sortedArray;
console.log(finalArray);

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

0

You could group first and then sort by the first item of each array.

If you have only positive 32 bit intger values, you could omit sorting, because the object is sorted like an array.

const
    array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20],
    result = Object
        .values(array.reduce((r, v) => {
            (r[v] ??= []).push(v);
            return r;
        }, {}))
        .sort(([a], [b]) => a - b);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório

0

Here is a shorter version than yours and more readable than Nina's

let array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20]

const finalArray = array.slice(0) // copy the array
  .reduce((acc,cur) => {
    const idx = acc.findIndex(item => item[0] === cur);
    if (idx !=-1) acc[idx].push(cur); // just push
    else acc.push([cur]); // push as array
    return acc
  },[])
  .sort(([a],[b]) => a-b); // sort on the first entry

console.log(finalArray);

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