-2

Here is my code:

function fix(arr) {
var x = arr.pop();
var y = arr.splice(0, 1);
arr.unshift(x);
arr.push(y);
return arr;
}

The output gives the array elements in the order I need. It has an extra ] at the end of the array which I can't figure out how to get rid of.

Artzelij
  • 1
  • 1

2 Answers2

1

The arr.splice(0, 1); call returns an array. You can replace it with Array#shift that returns a single item:

var arr = [1, 2, 3, 4, 5, 6, 7];

function fix(arr) {
  var x = arr.pop();
  var y = arr.shift();
  arr.unshift(x);
  arr.push(y);
  return arr;
}

fix(arr);

console.log(arr);

Or you can take the item from the array the slice creates:

var arr = [1, 2, 3, 4, 5, 6, 7];

function fix(arr) {
  var x = arr.pop();
  var y = arr.splice(0, 1);
  arr.unshift(x);
  arr.push(y[0]);
  return arr;
}

fix(arr);

console.log(arr);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

You get an array with

var y = arr.splice(0, 1);

After inserting, you keep this array in the actual array.


You could swap the first and the last element with destructuring assignment.

function fix(array) {
    [array[0], array[array.length - 1]] = [array[array.length - 1], array[0]];
}

var arr = [1, 2, 3, 4, 5, 6, 7];

fix(arr);
console.log(arr);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392