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

158
Vistas
sort and rearrange arrays basked on key value pair objects in javascript

I have 3 or more arrays that show prices (p) based on weight (w) breakpoints with unique identifiers for every array (i) such as the bellow.

var arr1 = [{w:1,p:10,i:"car1"},{w:2,p:15,i:"car1"},{w:3,p:21,i:"car1"}]
var arr2 = [{w:1,p:12,i:"car2"},{w:2,p:13,i:"car2"},{w:3,p:22,i:"car2"}]
var arr3 = [{w:1,p:9,i:"car3"},{w:2,p:12,i:"car3"},{w:3,p:33,i:"car3"}]

I want to generate "pricelist" arrays based cheapest, second cheapest, third cheapest etc.. such

var cheap1 = [{w:1,p:9,i:"car3"},{w:2,p:12,i:"car3"},{w:3,p:21,i:"car1"}]
var cheap2 = [{w:1,p:10,i:"car1"},{w:2,p:13,i:"car2"},{w:3,p:22,i:"car2"}]
var cheap3 = [{w:1,p:12,i:"car2"},{w:2,p:15,i:"car1"},{w:3,p:33,i:"car3"}]

what could be the fastest way to produce such an output.

I tried merging them into one array then sorting them out then looping over the array and pushing the objects into the new arrays based on if the indexes of the objects that had (w) value was equal to the previous (w) value, but it just wouldn't work and i cant seem find a way to solve this.

i tried multiple if then statements in multiple for loops and that worked out but the issue is that i might have some 20 arrays that i want to compare and if statements wont be viable.

appreciate the help!

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

0

You could sort by w property first and then by p. For getting a result of the sorted array pushthe object to the array by the remainder of the index.

const
    array1 = [{ w: 1, p: 10, i: "car1" }, { w: 2, p: 15, i: "car1" }, { w: 3, p: 21, i: "car1" }],
    array2 = [{ w: 1, p: 12, i: "car2" }, { w: 2, p: 13, i: "car2" }, { w: 3, p: 22, i: "car2" }],
    array3 = [{ w: 1, p: 9,i: "car3" }, { w: 2, p: 12,i: "car3"  }, { w: 3, p: 33, i: "car3" }],
    [cheap1, cheap2, cheap3] = [...array1, ...array2, ...array3]
        .sort((a, b) => a.w - b.w || a.p - b.p)
        .reduce((r, o, i) => {
            (r[i % 3] ??= []).push(o);
            return r;
        }, []);

console.log(cheap1);
console.log(cheap2);
console.log(cheap3);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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