Array.splice() method

Tell us what’s happening:
Describe your issue in detail here.

Hi, based on the challenge given, this is how I submitted my solution and for some reason it’s wrong.

Kindly advise what’s wrong with my solution.

 **Your code so far**

const arr = [2, 4, 5, 1, 7, 5, 2, 1];
// Only change code below this line
function splicedArr(arr) {
      return arr.splice(1,3)

}
// Only change code above this line
console.log(splicedArr(arr));
 **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36

Challenge: Remove Items Using splice()

Link to the challenge:

First problem that I see is that you ignored the instructions not to change code below this comment. In this case, the change you made is masking the problem with your code.

Second problem that I see is that your final array contents do not sum to 10. You’re cutting out a part that sums to 10 instead of leaving behind a part that sums to 10.

Note, you’re making this harder by creating a function instead of just using .splice() directly.

Yes , I made error by using a function but, from my understanding arr.splice(1,3) results to [4, 5, 1] which when summed up results to 10.

But from the solution provided the result is arr.splice(1,4) results to [ 4, 5, 1, 7 ] which sums up to 17.

Your changes below the comment are confusing you. You need to focus on what is left behind in the arr, not what is .slice()d out of arr.

By logging the result of your function call instead of logging the arr, you are looking at the wrong thing and it’s giving you misleading information.

Look at this:

const arr = [2, 4, 5, 1, 7, 5, 2, 1];
// Only change code below this line
arr.splice(1, 3);
// Only change code above this line
console.log(arr);

Well, an array in JavaScript is a special kind of object and as such is mutable. The splice() modifies the array but it also returns the part of the array that was chopped off.

Now,

let arr = [2, 4, 5, 1, 7, 5, 2, 1];
calling splice() on arr,
arr.splice(1, 4) // returns [4, 5,1,7] but it also mutates our array arr.

Currently, arr holds [2, 5, 2,1] which adds up to 10;

But using splice(1, 3), arr will hold [2, 7, 5, 2, 1] which adds up to 17.

Hope this helps…

1 Like

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