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

JavascriptWeb DevelopmentFront End Technology

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 ]
raja
Published on 19-Apr-2021 07:15:12
Advertisements