0

I wrote the code below in an attempt to add an element to the beginning of a new array and return that new array. It works fine, but when I return arr instead of newArr, the arr has changed as well.

function addToFrontOfNew(arr, element) {
  newArr = arr;
  newArr.unshift(element);
  return newArr;
}

If I were to write:

 function addToFrontOfNew(arr, element) {
  newArr = arr;
  newArr.unshift(element);
  return arr;
}

and test the function with addToFrontOfNew([1,2], 3) the function would return [3, 1, 2].

How can I rewrite the function so that the original arr is not modified along with the newArr?

  • 1
    `return [element].concat(arr)` – E. Sundin Aug 07 '17 at 20:18
  • 2
    That's because in your code both `newArr` and `arr` refer to the same array. You are not cloning the array. Check https://stackoverflow.com/questions/3978492/javascript-fastest-way-to-duplicate-an-array-slice-vs-for-loop – Ram Aug 07 '17 at 20:18

2 Answers2

1

You should clone the original array not reference it. One way is:

function addToFrontOfNew(arr, element) {
  newArr = arr.slice();
  newArr.unshift(element);
  return newArr;
}

slice() method returns a shallow copy... Here is the details https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

ihpar
  • 666
  • 4
  • 14
-1
function addToFrontOfNew(arr,element,rv)
{
    var len = arr.length;
    for(i=0; i<len; i++)
    {
        if (i==0) {
            newArr = [element,arr[0]];
        } else {
            newArr.push(arr[i]);
        }
    }

    switch(rv)
    {
        case 'arr':
            return arr;
        break;

        case 'newArr':
            return newArr;
        break;
    }

}
var fruit = ['cherries','apples','pears'];
var newElement = 'bananas';

console.log(addToFrontOfNew(fruit,newElement,'arr'));
console.log(addToFrontOfNew(fruit,newElement,'newArr'));

** FIXED THE CODE TO ADDRESS COMMENTS **

Added a switch statement so that the end-user could return either the original or new array. Basically it counts the original array, creates the new array if the increment = 0, adds the first element, then loops through the remainder of the array, pushing the remaining elements onto the array in sequence. The switch statement allows you to return the original or new array. Works in the console log, and if you output it to a tag using jQuery, just attach .toString() to the end of the function.