Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

126
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda