JS Hero help - set array

Hi all,

I realise this is a different website, but the two sites seem to reference each other, so hopefully it’s ok to post this.

I am working my way through JS hero’s test on JS and I’m totally stumped by one of them. It doesn’t have a solution and it’s really annoying that i can’t complete it. Does anyone happen to know the answer to this question? Sorry for total newbie question.

I can’t put links into posts yet (as i’m new to the forum), but here’s the question:

Just as you can get array elements by an index, you can set them by this index. It does not matter whether the array was previously filled or empty.

var languages = [];
languages[0] = 'C';
languages[1] = 'C++';
languages[2] = 'Java';

Here an empty array is filled successively with the listed values.

Exercise

Write a function setFirstElement that takes an array and an arbitrary variable. The variable should be inserted as the first element in the array. The array should be returned. setFirstElement([1, 2], 3) should return [3, 2] .

Useful method for inserting something into an array is splice(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

1 Like

var setFirstElement = function (array,x){
array[0]= x;
return array;
};