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

207
Visualizações
Sort a Chart from Lowest to Highest Value in Chart JS

I have this starting code and I'm tryng to figure out how I can sort this data from the highest to the lowest. The code can sort correctly the values but the labels in the yAxis are wrong.

I've tried myself but this code is advanced for me to understand.

Here's the snippet

//after the data is sorted
  let meta = chart.getDatasetMeta(0);
  let newMeta = [];
  let labels = chart.data.labels;
  let newLabels = [];
  

  meta.data.forEach((a, i) => {
    newMeta[dataIndexes[i]] = a;
    newLabels[dataIndexes[i]] = chart.data.labels[i];
  });

  meta.data = newMeta;
  chart.data.datasets[0].data = dataArray;
  chart.data.labels = newLabels;
    }
  }

The full code is here: https://jsfiddle.net/3seduh9k/

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

0

Here is the update:

if (chart.options.sort) {
      let labels = chart.data.labels;
      let dataArray = chart.data.datasets[0].data.slice();
      let mapValueLabel = {};
      dataArray.forEach((value, index) => {
        mapValueLabel[value] = labels[index];
      });
      // sort data array as well
      dataArray.sort((a, b) => b - a);
      let meta = chart.getDatasetMeta(0);
      let newLabels = [];
      dataArray.forEach((a, i) => {
        newLabels[i] = mapValueLabel[a];
      });
      chart.data.datasets[0].data = dataArray;
      chart.data.labels = newLabels;
        }
      }

Demo: https://jsfiddle.net/woL9ynpv/

My change is simple. I create the map to save value and label:

map{value:label}

After sorting value, we iterate the new list data array and assign label base on the value key.

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