This is not the classical backpack problem. Below, the problem that you want to try to solve.
You have a backpack, and in front of you there are n bags. Let us say three bags with different materials. E.g.: One for gold, one for silver, and another for copper. Each bag contains pieces of 1 unit (let's say 1g) for its material. You want to fill up the backpack in the way that you have the maximum value for the capacity of your backpack.
However, even with this specific proposition, there is a problem with the fragment below:
if (totalWeight === sorted[index].weight) {
index++;
}
For the first item, it would make sense, but then ... it does not. Maybe you should use another variable for partialWeight of each material.
Ex:
totalWeight++;
partialWeight++;
if (partialWeight === sorted[index].weight) {
index++;
partialWeight=0;
}