matrices: obtenga las 5 claves/valores más grandes en un objeto Javascript

CorePress2024-01-25  12

Soy nuevo en Javascript y estoy buscando la forma más eficaz de obtener las claves de los 5 valores más grandes de un objeto en un objeto nuevo.

por ejemplo, el objeto:

let object= {
  a: 5, 
  b: 87,
  c: 4,
  d: 33,
  e: 5, 
  f: 99,
  g: 1,
  h: 10,
  i: 3,
  j: 43,
};

volvería

object= {
  b: 87,
  d: 33,
  f: 99,
  h: 10,
  j: 43,
};

Sé que esto se puede hacer simplemente recorriendo cada elemento y comparándolo entre sí, pero me pregunto si hay una mejor manera de hacerlo en Javascript para mejorar el rendimiento.

Gracias,

2

El proceso es intrínsecamente iterativo; no se puede escapar de la necesidad de revisar las propiedades y recopilarlas.e valores más grandes.

- Puntiagudo

28/03/2021 a las 12:18



------------------------------------

Los convertiría en un mapa, los ordenaría, luego tomaría los primeros 5 y los convertiría nuevamente en un objeto. Aquí hay un desglose paso a paso:

const object= {
  a: 5, 
  b: 87,
  c: 4,
  d: 33,
  e: 5, 
  f: 99,
  g: 1,
  h: 10,
  i: 3,
  j: 43,
};

const newMap = Object.entries(object);

const sortedMap = newMap.sort((item1, item2) => item2[1] - item1[1]);

const top5Map = sortedMap.slice(0,5)

const top5 = Object.fromEntries(top5Map);

console.log(top5)

Respondido

28 de marzo de 2021 a las 12:40

AzC

AzC

71

4

4 insignias de bronce

1

Tenga en cuenta que esto no conserva el orden de claves original

-georg

28/03/2021 a las 13:24



------------------------------------

Sé que esto se puede hacer simplemente recorriendo cada elemento y comparándolos entre sí, pero me pregunto si hay una manera mejor...

Como dijo Pointy, este proceso es intrínsecamente iterativo, no se puede evitar un bucle y no se puede evitar al menos un pequeño bucle interno.

Esta es una forma de minimizar los bucles; consulte los comentarios:

// Start with an empty array
let top5 = [];
// Add [name, value] pairs to it
for (const key in object) {
    const thisValue = object[key];
    // Is this value greater than an existing one?
    // (This is a small inner loop, hidden in the `findIndex` call.)
    const index = top5.findIndex(([_, value]) => thisValue > value);
    if (index !== -1) {
        // Yes, insert it into the array at that location
        // (There's a small loop hidden here too: copying later entries
        // back one place in the array)
        top5.splice(index, 0, [key, thisValue]);
        // If the array is (now) > 5 entries, remove the last
        if (top5.length > 5) {
            top5.pop();
        }
    } else if (top5.length < 5) {
        // The value wasn't greater than an existing one, but
        // the array still needs values; add it at the end
        top5.push([key, thisValue]);
    }
}
// Convert back to an object
top5 = Object.fromEntries(top5);

En vivo:

let object= {
  a: 5, 
  b: 87,
  c: 4,
  d: 33,
  e: 5, 
  f: 99,
  g: 1,
  h: 10,
  i: 3,
  j: 43,
};
// Start with an empty array
let top5 = [];
// Add [name, value] pairs to it
for (const key in object) {
    const thisValue = object[key];
    // Is this value greater than an existing one?
    // (This is a small inner loop, hidden in the `findIndex` call.)
    const index = top5.findIndex(([_, value]) => thisValue > value);
    if (index !== -1) {
        // Yes, insert it into the array at that location
        // (There's a small loop hidden here too: copying later entries
        // back one place in the array)
        top5.splice(index, 0, [key, thisValue]);
        // If the array is (now) > 5 entries, remove the last
        if (top5.length > 5) {
            top5.pop();
        }
    } else if (top5.length < 5) {
        // The value wasn't greater than an existing one, but
        // the array still needs values; add it at the end
        top5.push([key, thisValue]);
    }
}
// Convert back to an object
top5 = Object.fromEntries(top5);
console.log(top5);

Tenga en cuenta que top5 siempre está en orden con el valor más alto primero, para minimizar qué tan lejos tenemos que llegar en la matriz eliminando el valor temprano si es menor que el valor más alto que conocemos (el primero en la matriz).

No he intentado mantener el orden de las propiedades, entre otras cosas porque, aunque las propiedades tienen orden (ahora), depender de ese orden casi siempre es una mala idea.

Su guía para un futuro mejor - libreflare
Su guía para un futuro mejor - libreflare