Removing the second number of the pair that add up to a target in JavaScript


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 −

 Live Demo

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 ]

Updated on: 19-Apr-2021

47 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements