Remove Items Using splice()

Tell us what’s happening:
let array = [‘I’, ‘am’, ‘feeling’, ‘really’, ‘happy’];

let newArray = array.splice(3, 2);
// newArray equals [‘really’, ‘happy’]
This newArray should be [‘I’, ‘am’, ‘feeling’] in my understanding. Cause you remove the last two items, right?
And I cannot figure out why my code is wrong.

Your code so far


function sumOfTen(arr) {
  // change code below this line
  arr = arr.splice(2,2);
  // change code above this line
  return arr.reduce((a, b) => a + b);
}

// do not change code below this line
console.log(sumOfTen([2, 5, 1, 5, 2, 1]));

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/remove-items-using-splice

splice() returns the removed elements, not the remaining.

function sumOfTen(arr) {
// change code below this line
arr.splice(1,2)
// change code above this line
return arr.reduce((a, b) => a + b);
}

// do not change code below this line
console.log(sumOfTen([2, 5, 1, 5, 2, 1]));

I didn’t get the idea. Does splice() removes signals as well, such as =,+ and >? I didn’t get.

Olivier, arr.splice(1,2) takes out the first 5 and the following 1, then reduce() sums 10 (2+5+2+1).

1 Like

Thanks!

Ppl really need to comment their explanation codes since many around us are in earlier stages.