Home > Blockchain >  sort and rearrange arrays basked on key value pair objects in javascript
sort and rearrange arrays basked on key value pair objects in javascript

Time:02-16

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!

CodePudding user response:

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; }

  • Related