-4

I need to move a selected item in an array to the start of the array. Lets say I have an array of 5 items

[{"A", "B", "C", "D", "E"}]. 

Now, say I choose index 2 (which will be C) and I need to move C (index 2) to the start of the Array. Finally the array should display as follows:

[{"C", "A", "B", "D", "E"}]. 
Sharon Watinsan
  • 9,620
  • 31
  • 96
  • 140
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift. While you're at it, read the doc of all the other methods. – JB Nizet Jun 21 '18 at 16:59
  • 2
    Possible duplicate of [Move an array element from one array position to another](https://stackoverflow.com/questions/5306680/move-an-array-element-from-one-array-position-to-another) – Nicholas Reynolds Jun 21 '18 at 17:04
  • 1
    this has nothing to do with Angular. – Reactgular Jun 21 '18 at 17:07
  • 2
    At least it would be great if someone can explain how this is done using `splice` than going ape ship downvoting ;/ – Sharon Watinsan Jun 21 '18 at 17:07
  • @sharonHwk have you read the documentation of this method? What does it do? What does it return? Have you tried using it? What did you try, what did you expect to happen and what happened instead? – JB Nizet Jun 21 '18 at 17:11

2 Answers2

0

Solution: You can solve your problem by using nested Array.Splice() methods. I would make this an extension method on arrays.

Array.prototype.move = function(from, to) {
    this.splice(to, 0, this.splice(from, 1)[0]);
};

Explanation: The inner splice() is essentially saying take the item you are wanting to move, remove it from the array, and use the value of that item in the outer splice(). The outer splice() is saying to insert the item you just removed from the array at the index you specified in to.

Array.prototype.move is Javascript's way of creating an extension method called move on array objects. Any code that has access to this function can call move(from, to) on any array (e.g. myArray.move(2, 0)). So I would put this somewhere global so all your code can see it!

Example:

var letters = ["A", "B", "C", "D", "E"];
letters.move(2, 0);
// letters is now ["C", "A", "B", "D", "E"]
0

Here an example, how to do it:

<script>
  var people = [
          {name: 'Collin', city: 'Omaha', friend: false},
          {name: 'Alice', city: 'New York', friend: false},
          {name: 'Pasha', city: 'Moscow', friend: true},
          {name: 'Denis', city: 'St. Pete', friend: true}
  ];

  function toBeginning(index)
  {
    var obj = people[index];
    people.splice(index, 1);
    people.unshift(obj);
  } 

  // To test it
  alert(people[0].name); // Alert: Collin
  toBeginning(2);        // move position 2 (Pasha) to Beginning
  alert(people[0].name); // Alert: Pasha

Sergio
  • 34
  • 5