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

132
Vistas
Link arrays in an object of arrays to sort by one of the arrays

I have an object with the following structure:

let obj = {
    "foo": ["orange", "apple", "pear", "grape", "lime"],
    "bar": [12, 6, 18, 3, 22],
    "bat": ["a", "b", "c", "d", "e"]
};

I want to sort by bar but also retain the order of foo and bat relative to bar, like so:

obj = {
    "foo": ["grape", "apple", "orange", "pear", "lime"],
    "bar": [3, 6, 12, 18, 22],
    "bat": ["d", "b", "a", "c", "e"]
};

Is there a tidy way to do this, or do I need to convert it to an array of arrays, sort by index (e.g., arr.sort((a,b) => a[1] - b[1]);), and convert back to the object?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

const obj = {
  "foo": ["orange", "apple", "pear", "grape", "lime"],
  "bar": [12, 6, 18, 3, 22],
  "bat": ["a", "b", "c", "d", "e"]
};

// get original indices of sorted bar
const indices = obj.bar
  .map((value, index) => ({ value, index }))
  .sort(({ value: a }, { value: b }) => a - b)
  .map(({ index }) => index);

// iterate over obj's values to reorder according to indices
const res = 
  Object.entries(obj)
  .reduce((acc, [key, value]) => ({ ...acc, [key]: indices.map(i => value[i]) }), {});

console.log(res);

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can create a temp array base on all values. Then you can sort that array based on bar. Once sorted, Just fill data to new response while iterating.

const obj = {
  foo: ["orange", "apple", "pear", "grape", "lime"],
  bar: [12, 6, 18, 3, 22],
  bat: ["a", "b", "c", "d", "e"],
};

const arr = obj.bar
  .map((bar, index) => ({
    bar,
    index,
  }))
  .sort((x, y) => x.bar - y.bar);
  
console.log(arr);

const res = arr.reduce(
  (map, { bar, index }, i) => {
    map.bar[i] = bar;
    map.foo[i] = obj.foo[index];
    map.bat[i] = obj.bat[index];
    return map;
  },
  { foo: [], bar: [], bat: [] }
);

console.log(res);

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