0

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?

1
  • Might be worthwhile tagging your question with javascript as well. I don't think there's anything typescript-specific about this. Commented Oct 10, 2018 at 7:46

1 Answer 1

2

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);

Sign up to request clarification or add additional context in comments.

3 Comments

I hold the value that user has selected and I want to re-arrange the array using the selected value. I'm confused as to how this solution could be used for this scenario.
So you need to find the index of the selected value first? Use indexOf().
Works perfect! Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.