Inelegant solution to Challenge:Remove Items Using splice() but without having to manually enter the splice parameters

Tell us what’s happening: My code would probably only work for the given array, is there a way to push the spliced items back into the array without causing problem with the arr.length?
Maybe better solutions would be in the algorithms section,
just wanted to put this code out there.
Describe your issue in detail here.

  **Your code so far**

const arr = [2, 4, 5, 1, 7, 5, 2, 1];
// Only change code below this line
let sum=0;
for (let i=0; i<arr.length; i++){
sum +=arr[i];
console.log(sum);
if (sum > 10){
  sum -=arr[i];
  console.log(sum);
  arr.splice(i,1);
  console.log(arr);
  i=i-1;
} else if (sum < 10){
  console.log("sum less than 10, continue process");
} else {
   console.log("Sum is exactly 10: ",arr);
}
}
// Only change code above this line
console.log(arr);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36

Challenge: Remove Items Using splice()

Link to the challenge:

Looking at the solution on the hints page this is all that is expected. The intent of this challenge is just to familiarize you with the splice method. You are not expected to create an algorithm that will solve this for any array thrown at you. So you can literally solve this challenge with just one line of code using splice by removing a range of elements from the array so that the remaining elements add up to 10.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.