Shaun
Shaun

Reputation: 471

How to add/sum the desired indexs of an array from specific array?

I have the following data structure and this data needs to be sorted by the sum of the first two indexes of an array in "104".

{
  "data":{
    "Org 1":{
      "102":[
        0.1444,
        0.1551,
        0.2369,
        0.3353,
        0.1282
      ],
      "104":[
        0.309,
        0.3483,
        0.218,
        0.0657,
        0.059
      ]
    },
    "Org 2":{
      "102":[
        0.19444444444444448,
        0.1388888888888889,
        0.19444444444444448,
        0.33333333333333326,
        0.1388888888888889
      ],
      "104":[
        0.20588235294117646,
        0.38235294117647056,
        0.14705882352941177,
        0.14705882352941177,
        0.1176470588235294
      ],
    },
    "Org 3":{
      "102":[
        0.0967741935483871,
        0.2903225806451613,
        0.16129032258064516,
        0.3548387096774194,
        0.0967741935483871
      ],
      "104":[
        0.44,
        0.24,
        0.2,
        0.04,
        0.08
      ]
    }
  }
}

How can I make this work? Can someone please help?

This is what I tried so far but it's not working as expected

let orgs = Object.keys(data);
let options = [];
let selection = orgs.forEach((data, d) => {
  data["104"].forEach((val, i) => {
    options[i].data.push(val);
  })
});

Upvotes: 0

Views: 61

Answers (1)

Zunayed Shahriar
Zunayed Shahriar

Reputation: 2723

First, we need to transform the data into an array for sorting.

Then define our own compare function as our requirement.

Finally, sort the array.

Run the snippet to check the result.

Solution:

var data = {
  "Org 1":{
    "102":[
      0.1444,
      0.1551,
      0.2369,
      0.3353,
      0.1282
    ],
    "104":[
      0.309,
      0.3483,
      0.218,
      0.0657,
      0.059
    ]
  },
  "Org 2":{
    "102":[
      0.19444444444444448,
      0.1388888888888889,
      0.19444444444444448,
      0.33333333333333326,
      0.1388888888888889
    ],
    "104":[
      0.20588235294117646,
      0.38235294117647056,
      0.14705882352941177,
      0.14705882352941177,
      0.1176470588235294
    ],
  },
  "Org 3":{
    "102":[
      0.0967741935483871,
      0.2903225806451613,
      0.16129032258064516,
      0.3548387096774194,
      0.0967741935483871
    ],
    "104":[
      0.44,
      0.24,
      0.2,
      0.04,
      0.08
    ]
  }
};

const transformedData = [];

Object.keys(data).forEach(
  f => {
    transformedData.push(data[f]);
  }
)

function compare(a, b) {
  var arrA = a["104"];
  var arrB = b["104"];

  if (arrA[0]+arrA[1] < arrB[0]+arrB[1]) {
    return -1;
  }
  if (arrA[0]+arrA[1] > arrB[0]+arrB[1]) {
    return 1;
  }
  
  return 0;
}

transformedData.sort(compare);
console.log(transformedData);

Breakdown:

(0.205882352941176 + 0.38235294117647) < (0.309 + 0.3483) < (0.44 + 0.24)

Upvotes: 1

Related Questions