Skip to content Skip to sidebar Skip to footer

Return The Last Item In An Array To First Spot

Is there a better approach to my code below. my code is working, but I'm just wondering if there is a better way to it. I have an array and i want to return the last item in this a

Solution 1:

You can use Pop with destructing.

let arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
let last = arr.pop()
let final = [last,...arr]

console.log(final)

Solution 2:

constreplce = arr => {
   return arr.unshift(arr.pop()) && arr;
};

console.log(replce(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']));

Short and sweet.

Solution 3:

Two variables values can be swapped in one destructuring expression. Please refers to doc Destructuring assignment

var arr = ['a', 'b', 'c', 'd','e','f','g','h'];
[arr[0], arr[arr.length-1]] = [arr[arr.length-1], arr[0]];
console.log(arr);

Solution 4:

You can use unshift() with pop() Refer this. Unshift adds an element to the first index in the array

constreplce = arr => {
   let n = arr.pop();
   arr.unshift(n)
   return arr;
};
console.log(replce(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']));

Solution 5:

unshift() will add to the start of an array, and pop() will remove from the end of the array. Example below will show you how to do this.

constreplace = arr =>{
	let tempvalue = arr.pop();
	arr.unshift(tempvalue);
	return arr;
}
console.log(replace(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']));

Not sure if I would call it better as I have not tested for speed, but it is easier to read.

Post a Comment for "Return The Last Item In An Array To First Spot"