1

function reverse(array,item){
  let word = Math.ceil(array.length/2)
  return array.splice(word,0,item)
}

console.log(reverse([1,2,4,5,6],3))

I was wondering why I'm getting a an empty array when the I call the function, instead of [1,2,3,4,5,6]?

Code Maniac
  • 37,143
  • 5
  • 39
  • 60

4 Answers4

3

Array#splice returns the items of the second parameter's count, the items who are deleted.

For returning the array, you need to return then array and not the spliced items.

function reverse(array, item) {
    let word = Math.ceil(array.length / 2);
    array.splice(word, 0, item);
    return array;
}

console.log(reverse([1, 2, 4, 5, 6], 3));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

splice does not return a new array, it modifies the input array. you need to return explicitly

function reverse(array,item){
  let word = Math.ceil(array.length/2)
  array.splice(word,0,item)
  return array
}

console.log(reverse([1,2,4,5,6],3))
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
1

array.splice(...) does not return a new array, it modifies the input array. Per MDN, its return value is:

An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

If your intention is to create a function that inserts without modifying the original array, here's a good example: https://stackoverflow.com/a/38181008/1266600.

sushain97
  • 2,752
  • 1
  • 25
  • 36
0

splice() changes the original array whereas slice() doesn't.

If you don't want to alter the original array, use slice.

function reverse(array,item){
  let word = Math.ceil(array.length/2)
  return [].concat(array.slice(0,word - 1), item, array.slice(word - 1));
}

console.log(reverse([1,2,4,5,6],3))
Asher G.
  • 4,903
  • 5
  • 27
  • 30