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

135
Visualizações
Convert an Array of arrays into one object with the same sort

I want to convert an Array of Arrays to one object with the same sort in javascript. My problem is the keys are in numbers and i just sorted the values as i want but when i convert the array to object by useing reduce it sort it again by keys.

const names = {
1: 'ياسر',
3: 'احمد'
}

const sorting = Object.entries(names)
               .sort((a, b) => a[1].localeCompare(b[1], "ar", { ignorePunctuation: true }))
               .reduce((acc, x) {
                 acc[x[0]] = x[1];
                 return acc;
                              }, {});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Objects don't preserve order of insertion when keys parsed as integers. So you can only append a string to the keys or use Map instead.

const names = {
3: 'D',
7: 'A',
5: 'B',
8: 'C'
}
names["4"] = "E";
console.log("names", names);

const object = Object.entries(names)
               .sort((a, b) => a[1].localeCompare(b[1], "ar", { ignorePunctuation: true }))
               .reduce((acc, x) => {
                acc[x[0]] = x[1];
                 return acc;
               }, {});
console.log("as object", object);
const objectString = Object.entries(names)
               .sort((a, b) => a[1].localeCompare(b[1], "ar", { ignorePunctuation: true }))
               .reduce((acc, x) => {
                acc["_" + x[0]] = x[1];
                 return acc;
               }, {});

console.log("as object w/string", objectString);
const map = Object.entries(names)
               .sort((a, b) => a[1].localeCompare(b[1], "ar", { ignorePunctuation: true }))
               .reduce((acc, x) => {
                acc.set(x[0], x[1]);
                 return acc;
               }, new Map());
console.log("as map", map, "look in devtools");

[EDIT] There is a way utilize proxy, which will allow "hide" prefix of the keys:

const names = {
3: 'D',
7: 'A',
5: 'B',
8: 'C'
}
names["4"] = "E";
console.log("names", names);

function sortObject(obj)
{
  const prefix = "___";
  return new Proxy(
    /* proxy target */
    Object.entries(obj)
     .sort((a, b) => a[1].localeCompare(b[1], "ar", { ignorePunctuation: true }))
     .reduce((acc, x) => (acc[prefix + x[0]] = x[1], acc), {})
    ,
    { /* proxy handler */
      get(target, key)
      {
        return typeof key == "string" ? target[prefix + key] : target[key];
      },
      set(target, key, value)
      {
        target[prefix + key] = value;
      },
      ownKeys: target => Object.keys(target).map(e => e.substring(prefix.length)), //remove prefix
      getOwnPropertyDescriptor: (target, key) => ({ enumerable: true, configurable: true })
    });
}
let proxy = sortObject(names);

proxy[0] = "AA"; //new properties added to the end

console.log("proxy added new entry to the end", proxy);

proxy = sortObject(proxy); //we can sort it again

console.log("proxy sorted with new entry", proxy);

console.log("it's enumerable too!");
for(i in proxy)
  console.log("key:", i, "value:", proxy[i]);

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