Array manipulation


#1

Hi all,

Sorry this question is not really meteor specific.

i have an array in meteor collection, i need to rearrange the array in a specific way.

e.g:
sample array = [ 1, 2, 3, 4, 5, 6 ]

when user select 3 on sample array, i need to move element from 3 till end to the beginning resulting:

[ 3, 4, 5, 6, 1, 2 ]

when user select 5 on sample array, the require result will be:

[ 5, 6, 1, 2, 3, 4 ]

if user select 2 on sample array the result will be:

[ 2, 3, 4, 5, 6, 1 ]

any array method can do this? i don’t mind its vanilla js, underscore or lo dash.

please advice, thanks.


#2

This will do it:

const sample = [1, 2, 3, 4, 5, 6];
const value = 5;              // chosen value
while (sample[0] !== value) { // while first element isn't chosen value
  const el = sample.shift();  // removes first element from array
  sample.push(el);            // adds element to the end of the array
}
console.log(sample); // [ 5, 6, 1, 2, 3, 4 ]

Merry Christmas.


#3

thanks and Merry Christmas…