JasonJohnson
JasonJohnson

Reputation: 19

Add "1" to the start and end of an Array

I'm trying to write a function to add a "1" to the start and end of an array.

Code I tried:

var addTwo = function(array) { 

    var myArray = array;
    var arrayLength;

    arrayLength = array.unshift(1);
    arrayLength = array.push(1);
    return myArray;
};

Upvotes: 0

Views: 76

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075039

The only issues I can see with your function are that you're doing

myArray;

at the end, which doesn't do anything useful, you're not using the arrayLength variable for anything, and you don't need the myArray variable. The unshift and push are fine.

So perhaps:

var addTwo = function(array) { 
    array.unshift(1);
    array.push(1);
    return array;
};

The only reason you need to return array is if the caller doesn't already have a handy reference to it.

Usage examples:

var a = ["apple","orange","banana"];
addTwo(a);
console.log(a); // [1, "apple", "orange", "banana", 1]

var addTwo = function(array) {
  array.unshift(1);
  array.push(1);
  return array;
};

var a = ["apple","orange","banana"];
addTwo(a);
console.log(a); // [1, "apple", "orange", "banana", 1]

and

var a = addTwo(["apple","orange","banana"]);
console.log(a); // [1, "apple", "orange", "banana", 1]

var addTwo = function(array) {
  array.unshift(1);
  array.push(1);
  return array;
};

var a = addTwo(["apple","orange","banana"]);
console.log(a); // [1, "apple", "orange", "banana", 1]

Upvotes: 1

Related Questions