Javascript 子集和-获取数组索引而不是值
我有以下功能:Javascript 子集和-获取数组索引而不是值,javascript,arrays,Javascript,Arrays,我有以下功能: function createSubsets(numbers, target) { // filter out all items larger than target numbers = numbers.filter(function (value) { return value <= target; }); // sort from largest to smallest numbers.sort(function (a, b) {
function createSubsets(numbers, target) {
// filter out all items larger than target
numbers = numbers.filter(function (value) {
return value <= target;
});
// sort from largest to smallest
numbers.sort(function (a, b) {
return b - a;
});
// array with all the subsets
var result = [];
while (numbers.length > 0) {
var i;
var sum = 0;
var addedIndices = [];
// go from the largest to the smallest number and
// add as many of them as long as the sum isn't above target
for (i = 0; i < numbers.length; i++) {
if (sum + numbers[i] <= target) {
sum += numbers[i];
addedIndices.push(i);
}
}
console.log(addedIndices);
// remove the items we summed up from the numbers array, and store the items to result
// since we're going to splice the numbers array several times we start with the largest index
// and go to the smallest to not affect index position with splice.
var subset = [];
for (i = addedIndices.length - 1; i >= 0; i--) {
subset.unshift(numbers[addedIndices[i]]);
numbers.splice(addedIndices[i], 1);
}
result.push(subset);
}
return result;
}
函数创建子集(数字、目标){
//筛选出大于目标的所有项目
数字=数字。过滤器(函数(值){
返回值(0){
var i;
var总和=0;
var addedices=[];
//从最大数到最小数,然后
//只要总数不超过目标,就添加尽可能多的
对于(i=0;i if(sum+numbers[i]当你有值时,你可以找到它的索引。在开始时使用filter函数你可以创建一个新的数组,因此找到的索引将与原始的索引不匹配。你不能只做:subset.unshift(addedIndices[i]);当您到达while循环数数组时,它不是原始数组。它是经过排序和筛选的。请记住。