What i have to do in this problem is to add all the numbers based on each integer's sign.
Signs array has Boolean type as each element. 'true' element represents a positive element, but 'false' means a negative one.
Step by step, i thought of changing each element of absolutes to interger according to a real sign and add all numbers using 'reduce' method.
function solution(ab, signs) {
const real = ab.map((num, idx)=> {
return signs[idx] === false ? -num : +num
})
return real.reduce((acc,cur)=> acc+cur, 0)
}
This can be passed in all cases. But, wanted to make them shorter and more effective, I searched a best code and noticed that 'reduce' method can be used a lot.
function solution(absolutes, signs) {
return absolutes.reduce((acc, val, i) => acc + (val * (signs[i] ? 1 : -1)), 0);
}
Surprisingly, multiply 1 or -1 by curent element was the key point to solve this problem. It didn't need to change each to a real sign, If being dealt with addition to multiplied sign by current value. What a amazing !