I encountered a challenging question in my office, which I could not solve.
const array = [2, 7, 11, 15], target = 9;
In the above I have an array and target as 9, as well this target can change any of value as 18,26 like so. The result should show the indexOf array which used for get the target. For example at present it is 9, so the result should be [0,1] (2+7). If the target is 26 then result should be [2,3]. How to achieve this?
For my try the first attempt is working. but rest of them not. What can I try next?
My code:
const array = [2, 7, 11, 15], target = 9;
const result = [];
const outPut = array.reduce((c,v,i,a) => {
if(c !== target && c < target) {
result.push(a.indexOf(v));
}
return c + v;
}, 0);
console(result);