2

How can I arrange an array like a gaussian function, meaning max values in the middle, min values in edges?

e.g.

var Array = [5,2,7,4,1]

will output the following array:

[1,4,7,5,2]

2 Answers 2

4

I didn't used underscore functions but you can use equivalent function from underscore/lodash to shorten code.

Steps:

  1. Sort the array in descending order
  2. Iterate over array and add the elements from sorted array at the start and end alternately

var arr = [5, 2, 7, 4, 1];

var sortedArr = arr.sort(function(a, b) {
  return b - a;
});

var gaussianArr = [];

sortedArr.forEach(function(e, i) {
  if (i % 2) {
    gaussianArr.push(e);
  } else {
    gaussianArr.unshift(e);
  }
});

console.log(gaussianArr);
document.write(gaussianArr);

Want underscore solution?

Here you go. fiddle. You won't see much difference between Vanilla JS solution and underscore solution(as the logic is same, only different syntax).

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

Comments

1

Here is the logic.

function gSort(arr) {
    var _a = arr.slice()
    _a.sort(function(a,b){return a-b});
    _a.reverse();
    var _isstart = false;
    var _out = [];
    for (var i = 0; i < _a.length; i++) {
        if (i%2) {
           _out.push(_a[i])
        }else{
           _out.splice(0,0,_a[i]); //You can use _out.unshift(_a[i]); also
        }
    }
    return _out;
}

var array = [5,2,7,4,1]
console.log(gSort(array));

2 Comments

@Tushar, Updated answer, Thanks for suggestion.

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.