0

The object collection is

[Object, Object, Object, Object, Object, Object, Object, Object, Object]

Each object has a number of elements in it as such

{value1: someValue, valueIWantToSort: someNumericValue, value2: someValue, value3: someValue,...}

Now I want to put the object in order based on the value of valueIWantToSort. Where valueIWantToSort is a number.

gunr2171
  • 16,104
  • 25
  • 61
  • 88

1 Answers1

-2

First of all the documentation, to read !

TL;DR : We use a comparator function passed to the native sort function of arrays !

//[Object, Object, Object, Object, Object, Object, Object, Object, Object];
    /*
    {
        value1: someValue, 
        valueIWantToSort: someNumericValue, 
        value2: someValue, 
        value3: someValue,
    ...}
    */

var myArray=[];
var i=0;
for(i;i<10;i++){
  myArray.push({
        value1: 'someValue', 
        valueIWantToSort: Math.round(Math.random() *100 ) ,
        value2: 'someValue', 
        value3: 'someValue',
  });
};
document.body.innerHTML += "Before sorting :<br> " + JSON.stringify( myArray ) + "<hr>";

myArray.sort( function(a,b){ return  a.valueIWantToSort > b.valueIWantToSort })


document.body.innerHTML += "After sorting :<br> " + JSON.stringify( myArray ) + "<hr>";

myArray.sort( function(a,b){ return  a.valueIWantToSort < b.valueIWantToSort })
// here we invert the sort order -----------------------^

document.body.innerHTML += "After sorting inverted:<br> " + JSON.stringify( myArray );
Anonymous0day
  • 3,012
  • 1
  • 14
  • 16
  • `Array.prototype.sort` receives a `function` that must return a number, either below 0, 0 or greater than 0. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – arg20 Oct 16 '15 at 19:02
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – gunr2171 Oct 16 '15 at 19:12
  • @arg20 and to be complete [Arithmetic_Operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators) – Anonymous0day Oct 16 '15 at 19:26