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]
Dor Cohen
  • 16,769
  • 23
  • 93
  • 161

2 Answers2

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

Tushar
  • 85,780
  • 21
  • 159
  • 179
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));
Laxmikant Dange
  • 7,606
  • 6
  • 40
  • 65
  • 1
    Don't rely on `sort` to sort numbers. http://stackoverflow.com/questions/1063007/how-to-sort-an-array-of-integers-correctly http://stackoverflow.com/questions/7000851/array-sort-doesnt-sort-numbers-correctly – Tushar Sep 20 '15 at 10:37
  • 1
    @Tushar, Updated answer, Thanks for suggestion. – Laxmikant Dange Sep 20 '15 at 12:38