Problem
We are required to write a JavaScript function that takes in an array of numbers and a target sum.
Our function should remove the second number of all such consecutive number pairs from the array that add up to the target number.
Example
Following is the code −
const arr = [1, 2, 3, 4, 5];
const target = 3;
const removeSecond = (arr = [], target = 1) => {
const res = [arr[0]];
for(i = 1; i < arr.length; i++){
if(arr[i] + res[res.length-1] !== target){
res.push(arr[i]);
};
};
return res;
};
console.log(removeSecond(arr, target));Output
Following is the console output −
[ 1, 3, 4, 5 ]