let getIndex = (_list, target) => {
let xiaoyu = _list.map((key, index) => { return { key, index } }).filter(m=> m.key <= target);
let getzuhe = (arr) => {
let _getzhe = (_arr) => {
if (_arr.length == 1) return _arr;
let arr1 = _getzhe(_arr.slice(1));
let map1 = arr1.map(m => `${_arr[0]},${m}`);
let map2 = _getzhe(_arr.slice(1));
let map3 = [_arr[0]];
return map1.concat(map2, map3);
}
let map = _getzhe(Array.from({ length: arr.length }, (_, i) => i))
.map(m=>(m+'').split(',').map(m=>parseInt(m)));
return map.map(m => m.map(i => arr[i]));
}
let zuhes = getzuhe(xiaoyu);
console.log('有效长度>',xiaoyu.length);
console.log('组合数>',zuhes.length);
let jiejin = [];
zuhes.forEach(zuhe => {
let he = zuhe.map(m=>m.key).reduce((t, v) => t+v);
let indexs = zuhe.map(m=>m.index).reduce((t, v) => t+v);
if (he <= target) {
jiejin = jiejin.filter(m => m.he >= he);
if (jiejin.length == 0 || jiejin.some(m => he >= m.he)) {
jiejin.push({ zuhe, he, indexs, length: zuhe.length });
}
}
})
return jiejin.filter(m => m.indexs == Math.min.apply(null, jiejin.map(m => m.indexs)));
}
let list = [1000, 2000, 500, 1500, 3456, 57, 67, 345, 2346456, 8, 4556, 78, 1267, 68689, 43];
let jieguo = getIndex(list, 3235);
console.log('计算结果>',JSON.stringify(jieguo));
console.log('最接近的组合是 >',jieguo.map(m=>m.zuhe.map((m=>m.key))));
console.log('最接近的值是 >',jieguo.map(m=>m.zuhe.map((m=>m.key)))[0].reduce((t,v)=>t+v,0));
console.log('最接近的角标是 >',jieguo.map(m=>m.zuhe.map((m=>m.index))));