Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!