
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Second Number of the Pair That Adds 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 −
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 ]
Advertisements