0

The goal of this code is to sort this array [1,2,3,4,5] to look like this [5,3,1,2,4]. I also want it to sort arrays that someone else sends me, so for example it should work with [-10,-1,-4] as [-1,-10,-4]. The array should be sorted using this rules:

  • Smallest number is in the middle.
  • Number higher than the smallest one should be right to it [2](In first example).
  • Number higher than [2](In the first example) should be left from [1](In the first example).

So far this is my idea:

let values = [1,2,3];
let storage = values.sort((a, b) => a - b);
let result = storage[0];

for( let i = 1; i <= (values.length/2); i+=2 ){
    result.unshift (storage[i]);
    result.push (storage[i+1]);

}
return result);

But I can't make it work, I'm lost on what I can change at the moment.

3 Answers 3

1

You could take a butterfly sorting which sorts odd numbers descending and even numbers ascending.

var array = [1, 2, 3, 4, 5];

array.sort((a, b) => b % 2 - a % 2 || (a % 2 ? b - a : a - b));

console.log(array);

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

1 Comment

Best solution, a bit hard for me to understand tho ":D .
1

You need to make result an array:

let values = [1,2,3];
let storage = values.sort((a, b) => a - b);
let result = [storage[0]];  // make the result an array

for( let i = 1; i <= (values.length/2); i+=2 ){
    result.unshift (storage[i]);
    result.push (storage[i+1]);
}
console.log(result);

1 Comment

Thanks a lot, I can't understand how i managed to miss the fact it was not an array.
1

Here is my solution

function customSort(inputArray){
  var initialSort = inputArray.sort()

  var finalSorted = []
  finalSorted.push(initialSort[0])
  //console.log(finalSorted)
  for(i=1;i<initialSort.length;i++){
    if(i%2 === 0){
      finalSorted.unshift(initialSort[i])
    }
    else{
      finalSorted.push(initialSort[i])
    }
  
  }
  
  console.log(finalSorted)
  
}

var inputArray = [1,2,3,4,5]

customSort(inputArray)

1 Comment

Thank you very much, this was the solution I was looking for !

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.