# javascript – Best combination of a sum between two parameters in an array of objects

I am trying to build a simple algorithm to achieve the best combination of values based on two params in an array of objects.

The whole code is available here

First I have an array holding objects. The items which will be analyzed and packed into volumes together. All of the values are in percentages.

``````const nonStackableItems = (
{
id: 0,
m2: 15,
m3: 11,
weight: 20
},
{
id: 1,
m2: 25,
m3: 12,
weight: 42
},
{
id: 2,
m2: 50,
m3: 13,
weight: 40
},
{
id: 3,
m2: 65,
m3: 14,
weight: 25
}
);
``````

The idea is to combine these objects into packages, respecting the `maximum` of 100% for each value (except for `m3` in this case, as all the packages should have enough `height` in this first analysis).

The approach that I gave is just not good enough, as I am sorting this `array` by `m2` then by `weight`, call the `function` and then compare the length of both, and then choose the result that creates less volumes.

This is the piece of code that does the calculations:

``````function nSVolHelper(arr, vol, param1, param2) {
let newVol = {
id: vol.length,
m2: 0,
m3: 0,
weight: 0
};
for (let i = 0; i < arr.length; i++) {
const validation =
newVol(param1) + arr(i)(param1) < 100 &&
newVol.m2 + arr(i)(param2) < 100;
if (validation) {
newVol.m2 += arr(i).m2;
newVol.m3 += arr(i).m3;
newVol.weight += arr(i).weight;
}
if (!validation) {
return nSVolHelper(arr.slice(i), (...vol, newVol), param1, param2);
}
}
vol.push(newVol);
return vol;
}

function nSVol(arr, param1, param2) {
return nSVolHelper(arr, (), param1, param2);
}
``````

I would like to find a way of doing this without taking as a base the order of the `array`, to get the finest calculation without running unnecessary code, and I get the feeling that this approach of mine is just not reliable as well.

As an example, for better understanding:

If I pass the array sorted by `weight` I get a create 2 volumes.

``````console.log(
"call",
nSVol(
nonStackableItems.sort((a, b) => a.weight - b.weight),
"weight",
"m2"
)
``````

If I pass this same `array` sorted by `m2` I get 3 volumes.

``````console.log(
"call",
nSVol(
nonStackableItems.sort((a, b) => a.m2 - b.m2),
"weight",
"m2"
)
``````

This was the best approach that I could find, but I feel that there could be another way of thinking of this.