arrays - Ranking Values in Javascript object -


what @ values "water" , rank them lowest highest adding new key:value in.

however if value of water same want assign same rank.

so far have this, works in orders assigns rank, unsure how can check other values see if same. if same guess assign 'index' instead of 'index + 1'

var results = {     schedules: [         { water: 10326.11, milk: 231.27, cola: 171.85 },         { water: 10326.11, milk: 231.27, cola: 171.85 },         { water: 1500, milk: 231.27, cola: 171.85 }     ] };  results = _(_.sortby(results.schedules, "water")).foreach(function (water,    index) { water.waterrank = index + 1; });  console.log(results); 

js fiddle here

store previous value , previous index, check if value repeating , assign index. this

var index = 0, prevvalue = 0; _(_.sortby(results.schedules, "water")).foreach(function (water, i) {     if(prevvalue != water.water) index++;     prevvalue = water.water;     results.schedules[i].waterrank = index; }); console.log(results.schedules); 

var results = {    "schedules": [{      "water": 10326.11,      "milk": 231.27,      "cola": 171.85    }, {      "water": 10326.11,      "milk": 231.27,      "cola": 171.85    }, {      "water": 1500,      "milk": 231.27,      "cola": 171.85    }, {      "water": 1500,      "milk": 231.27,      "cola": 171.85    }, {      "water": 10500,      "milk": 231.27,      "cola": 171.85    }, {      "water": 10500,      "milk": 231.27,      "cola": 171.85    }]  };    var index = 0,    prevvalue = 0;  _(_.sortby(results.schedules, "water")).foreach(function(water, i) {    if (prevvalue != water.water) index++;    prevvalue = water.water;    results.schedules[i].waterrank = index;  });  console.log(results.schedules);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.2.1/lodash.min.js"></script>


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -