Hamidou Diallo
Hamidou Diallo

Reputation: 13

How do I add an item to the middle of an array?

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

Upvotes: 1

Views: 1608

Answers (4)

Asher G.
Asher G.

Reputation: 5001

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

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

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

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386680

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

Upvotes: 3

sushain97
sushain97

Reputation: 2802

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.

Upvotes: 1

Related Questions