Question: I got an array 

```
var myArray = [5,8,1,4,2,9,3,7,6];

```

I want the output to be `[ 9, 1, 8, 2, 7, 3, 6, 4, 5 ]`. I tried the following code:

```
function firstAndLast(array) {
    var arr= [];
    array = myArray.sort().reverse();
    for(var i = 0; i < array.length; i++){
        var firstItem = myArray[i];
        var lastItem = myArray[myArray.length - 1];

        if(lastItem > firstItem){
            arr.push(array[i]);
    }}

var display = firstAndLast(myArray);

console.log(display);

```

Can anyone suggest what am I missing to achieve the targeted result? 

**What I want to acheive** is to arrange the array in even odd indexes where odd indexes contain larger values in descending order and even indexes contain values in ascending order

Answer: 
Your code actually fits your description, except this part:

```
if(lastItem > firstItem){
        arr.push(array[i]);
}

```

Why don't you just push both items to the array:

```
if(lastItem > firstItem){
        arr.push(firstItem, lastItem);
}

```

And the `lastItem` should be dependent on `i`:

```
var lastItem = array[array.length - i - 1];

```

Them you only have to

```
return arr;

```

At the end and it should work :)

```
 function firstAndLast(array) {
    const result = [];
    array = array.sort((a, b) => a - b).reverse();
    for(var i = 0; i < array.length; i++){
       var firstItem = array[i];
       var lastItem = array[array.length - i - 1];
       if(lastItem < firstItem){
          result.push(firstItem, lastItem);
       }
    }
   return result;
}

 var myArray = [5,8,1,4,2,9,3,7,6];
 console.log(firstAndLast(myArray));

```

Now this only omits the value in the middle, which you can easily add like this in the loop:

```
   if(firstItem === lastItem) {
     result.push(firstItem);
   }

```
Apparently you want to shuffle the array?

If that is the case the simplest way of doing it is just using this

```
function shuffle(array) {
  var m = array.length, t, i;

  // While there remain elements to shuffle…
  while (m) {

    // Pick a remaining element…
    i = Math.floor(Math.random() * m--);

    // And swap it with the current element.
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }

  return array;
}

```

It is Fisher-Yates shuffle.

More on it on the link : <https://bost.ocks.org/mike/shuffle/>

If that is not the case post a reply to the comment so we can find some new sorting logic!