-3

I have an array of objects in javascript:

shapeToolsTarget: Array(4)
0: {id: 20, name: "Background", type: "shape"}
1: {id: 21, name: "BorderColor", type: "shape"}
2: {id: 22, name: "BorderWeight", type: "shape"}
3: {id: 3, name: "Paste", type: "text"}

How I can rearrange the last element of an array to the first place? Like that:

shapeToolsTarget: Array(4)
0: {id: 3, name: "Paste", type: "text"}
1: {id: 20, name: "Background", type: "shape"}
2: {id: 21, name: "BorderColor", type: "shape"}
3: {id: 22, name: "BorderWeight", type: "shape"}
Moo
  • 1
  • 4

2 Answers2

3

You can use a combination of unshift() and pop().

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

var items = ['A', 'B', 'C'];
console.log(items);

items.unshift(items.pop());
console.log(items);
Community
  • 1
  • 1
vicpermir
  • 2,653
  • 3
  • 18
  • 27
  • Thank you! But I have 4 elements instead of 3 and i got 0: {id: 22, name: "BorderWeightComponent", type: "shape"} 1: {id: 3, name: "Paste", type: "text"} 2: {id: 20, name: "Background", type: "shape"} 3: {id: 21, name: "Border", type: "shape"} – Moo Feb 24 '20 at 12:56
  • 1
    The number and type of element in the array does not matter, I've added a description to clarify how both methods work. Just do `shapeToolsTarget.unshift(shapeToolsTarget.pop());`. – vicpermir Feb 24 '20 at 12:59
  • Okay! But I got this element on the 2nd place! Instead of first.. – Moo Feb 24 '20 at 13:01
0

You can use pop() & unshift() array methods for this like:

  • pop() removes the last element from the array.
  • unshift(value) adds the value to the beginning of the array.

let shapeToolsTarget = [
{id: 20, name: "Background", type: "shape"},
{id: 21, name: "BorderColor", type: "shape"},
{id: 22, name: "BorderWeight", type: "shape"},
{id: 3, name: "Paste", type: "text"}];

shapeToolsTarget.unshift(shapeToolsTarget.pop())

console.log(shapeToolsTarget)
palaѕн
  • 64,836
  • 15
  • 100
  • 121
  • Thank you! But I got that one using ur code 0: {id: 22, name: "BorderWeightComponent", type: "shape"} 1: {id: 3, name: "Paste", type: "text"} 2: {id: 20, name: "Background", type: "shape"} 3: {id: 21, name: "Border", type: "shape"} It`s on the 2nd place.. – Moo Feb 24 '20 at 12:58
  • Code updated. Please try again. – palaѕн Feb 24 '20 at 13:03