dwilbank
dwilbank

Reputation: 2520

trying to concatenate a single value to an array in javascript

I'm trying to produce a new_array consisting of old_array[0] + old_array2.slice(1)

I cannot see how concat would help me here, unless I create a 3rd temporary array out of old_array[0].

Is that the only way to do it?

Upvotes: 1

Views: 1520

Answers (3)

Kingpin2k
Kingpin2k

Reputation: 47367

var a = [1,2,3];

var b = [4,5,6];

Then you have two options depending on the result you want. Either:

var c = a.slice(1).concat(b[0]);

Or:

var c = [b[0]].concat(a.slice(1));

Upvotes: 1

Phil Nicholas
Phil Nicholas

Reputation: 3719

If you simply want a new two-element array from those explicitly defined portions of two source arrays, then just do this:

new_array = [old_array[0], old_array2.slice(1).toString()];

See: jsfiddle

(Note: Second element fixed from originally posed solution, per comment received.)

Upvotes: 0

Timothy Jones
Timothy Jones

Reputation: 22135

The function you are looking for is array.unshift(), which adds a value (or values) to the start of the array:

var fruits = [ "orange", "banana" ];
fruits.unshift("apple");
// Fruits is now ["apple", "orange", "banana"]

If you want to produce a new array, you could do this to the result of a slice:

var new_array = old_array2.slice(1);
new_array.unshift(old_array[0]); 

But, since this code just replaces the first element, you could also write:

var new_array = old_array2.slice(0);
new_array[0] = old_array[0]; // I prefer this for readability

I'm not sure about the slice(1) in your question, as I don't think it matches the wording of your question. So, here are two more answers:

  • If you want to create a new array which is the same as old_array2, but with the first value from old_array at the start of it, use:

     var new_array = old_array2.slice(0); // Note the slice(0)
     new_array.unshift(old_array[0]);
    
  • If you want to create a new array which is the same as old_array2, but with the first value replaced with the first value of old_array, use:

    var new_array = old_array2.slice(0);
    new_array[0] = old_array[0]; 
    

Upvotes: 1

Related Questions