Ali Celebi
Ali Celebi

Reputation: 1008

TypeScript - reposition elements in an array

I have following array that can have multiple elements in it.

"coachID" : [ 
     "choice1", 
     "choice2"
]

If user chooses choice2, I would like re-arrange its content as shown below.

"coachID" : [ 
     "choice2", 
     "choice1"
]

Similarly, if there are more than 2 elements in the array;

"coachID" : [ 
     "choice1", 
     "choice2",
     "choice3"
]

and user chooses choice2 element then array should be re-arranged as follows:

"coachID" : [ 
     "choice2", 
     "choice1",
     "choice3"
]

In essence, chosen element should always be placed at the beginning of the array.

How can I achieve this with TypeScript please?

Upvotes: 0

Views: 42

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97172

I don't think there's anything TypeScript-specific about this.

You can just use splice() to take the selected element out, and unshift() to add it back in at the beginning:

array.unshift(...array.splice(index, 1)); // index = index of the selected element

const data = [ 
     "choice1", 
     "choice2",
     "choice3"
];

const select = (array, i) => {
  if (array && array.length && i < array.length) {
    array.unshift(...array.splice(i, 1));
  }
};

console.log(data);

select(data, 1);

console.log(data);


If you want to base the operation on the value of the selected element, add a call to indexOf():

array.unshift(...array.splice(array.indexOf(value), 1)); // value = selected value

const data = [ 
     "choice1", 
     "choice2",
     "choice3"
];

const select = (array, value) => {
  if (array && array.length) {
    const i = array.indexOf(value);
    
    if (i > 0) { 
      array.unshift(...array.splice(i, 1));
    }
  }
};

console.log(data);

select(data, "choice2");

console.log(data);

Upvotes: 2

Related Questions