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

225
Visualizações
Javascript, Sort an array of numbers from highest to lowest but keep original index

I have an array of numbers that I want to sort from highest to lowest and still be able to keep the original array to reference the original indexes.

I have managed to accomplish what I want with the code here:

// Original array.
const originalArray = [3, 8, 2, 8, 6, 9, 8, 4];
// Creating a deep copy of an original array.
const deepCopy = [...originalArray].sort(function(a, b){
    return b-a
});
// result array
const arr = [];
// count to get the index based on duplicate values.
let count = 0;

// Iterating deepCopy array to get the actual index.
deepCopy.forEach((elem) => {
    // Checking for duplicate value in an array
    if(originalArray.indexOf(elem) === originalArray.lastIndexOf(elem)) {
        // This line of code execute if there is no duplicates in an array.
        arr.push(originalArray.indexOf(elem))
    }else{
        // This line of code execute if there is duplicate values in an array. 
        count++;
        // Inserting the index one by one.
        arr.push(originalArray.indexOf(elem, count))
    }
});

// Result array.
document.write("Original Array<br/>"+originalArray+"    : Original Array");
document.write("<br/><br/>");
document.write("Original Index<br/>"+arr+"  : Orignal Index");
document.write("<br/><br/>");
document.write("Deep Copy<br/>"+deepCopy+"  : Sorted Array");
document.write("<br/><br/>");
// Index[0] = Original Array [2];   
for(n=0; n<arr.length; n++){
    a2 = originalArray.indexOf(deepCopy[n]);
    document.write(n+"] "+originalArray[a2]+" - Original Index: "+a2+"<br/>");
};

document.write("<br/>For the Number 8 at position 1,2,3- The indexes shold read 1,3 & 6 instead of three consecutive 1's");

The problem I have is where there are duplicate numbers - in this case the number eight appears three times but when sorted it only return the index of the first incidence of the number - instead of displaying the indexes 1,3,6.

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

0

To elaborate @epascarello comment, you can map the copied array to include the index for each element before sorting. no need to separate indexes into a separate array.

// Original array.
const originalArray = [3, 8, 2, 8, 6, 9, 8, 4];
// Creating a deep copy of an original array.
const deepCopy = [...originalArray].map((e, i) => [e, i]).sort(function(a, b){
    return b[0]-a[0]
});

// Result array.
document.write("Original Array<br/>"+originalArray+"    : Original Array");
document.write("<br/><br/>");
document.write("Deep Copy<br/>"+deepCopy+"  : Sorted Array");
document.write("<br/><br/>");
 
let n = 0
for(let [e, i] of deepCopy){
    n++
    document.write(n+"] "+ e +" - Original Index: "+ i +"<br/>");
};

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