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]?

4 Answers 4

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));

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Nina! How would I go about appending the item in the middle of the array?
how should look the array then?
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))

Comments

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.

Comments

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))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.