Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Removing the second number of the pair that add up to a target in JavaScript
Problem
We need to write a JavaScript function that takes an array of numbers and a target sum. The function should remove the second number from any consecutive pair of numbers that add up to the target.
Example
Let's see how this works with a practical example:
const arr = [1, 2, 3, 4, 5];
const target = 3;
const removeSecond = (arr = [], target = 1) => {
const res = [arr[0]];
for(let 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));
[ 1, 3, 4, 5 ]
How It Works
The algorithm works by:
- Starting with the first element in the result array
- Checking each subsequent element against the last element in our result
- If they don't sum to the target, adding the current element
- If they do sum to the target, skipping the current element (removing the second number)
Step-by-Step Breakdown
const arr = [1, 2, 3, 4, 5];
const target = 3;
const removeSecondDetailed = (arr, target) => {
const res = [arr[0]]; // Start with first element: [1]
console.log("Initial result:", res);
for(let i = 1; i < arr.length; i++){
const currentSum = arr[i] + res[res.length-1];
console.log(`Checking ${arr[i]} + ${res[res.length-1]} = ${currentSum}`);
if(currentSum !== target){
res.push(arr[i]);
console.log("Added to result:", res);
} else {
console.log(`Sum equals target (${target}), skipping ${arr[i]}`);
}
}
return res;
};
console.log("Final result:", removeSecondDetailed(arr, target));
Initial result: [ 1 ] Checking 2 + 1 = 3 Sum equals target (3), skipping 2 Checking 3 + 1 = 4 Added to result: [ 1, 3 ] Checking 4 + 3 = 7 Added to result: [ 1, 3, 4 ] Checking 5 + 4 = 9 Added to result: [ 1, 3, 4, 5 ] Final result: [ 1, 3, 4, 5 ]
Another Example
const arr2 = [2, 4, 6, 1, 5];
const target2 = 6;
console.log("Original array:", arr2);
console.log("Target sum:", target2);
console.log("Result:", removeSecond(arr2, target2));
Original array: [ 2, 4, 6, 1, 5 ] Target sum: 6 Result: [ 2, 6, 1, 5 ]
Conclusion
This algorithm efficiently removes the second number from consecutive pairs that sum to a target value. It maintains the original order while processing elements sequentially, making it a simple yet effective solution for this specific array manipulation problem.
Advertisements
