Get "leaderboard" of list of numbers - javascript

I am trying to get a kind of "leaderboard" from a list of numbers. I was thinking of making an array with all the numbers like this
var array = [];
for (a = 0; a < Object.keys(wallets.data).length; a++) { //var wallets = a JSON (parsed) response code from an API.
if (wallets.data[a].balance.amount > 0) {
array.push(wallets.data[a].balance.amount)
}
}
//Add some magic code here that sorts the array into descending numbers
This is a great option, however I need some other values to come with the numbers (one string). That's why I figured JSON would be a better option than an array.
I just have no idea how I would implement this.
I would like to get a json like this:
[
[
"ETH":
{
"balance":315
}
],
[
"BTC":
{
"balance":654
}
],
[
"LTC":
{
"balance":20
}
]
]
And then afterwards being able to call them sorted descending by balance something like this:
var jsonarray[0].balance = Highest number (654)
var jsonarray[1].balance = Second highest number (315)
var jsonarray[2].balance = Third highest number (20)
If any of you could help me out or point me in the right direction I would appreciate it greatly.
PS: I need this to happen in RAW JS without any html or libraries.

You should sort the objects before making them a JSON. You can write your own function or use a lambda. See this [https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value]

Since you are dealing with cryptocurrency you can use the currency-code as a unique identifier.
Instead of an array, you can define an object with the currency as properties like this:
const coins = {
ETH: [300, 200, 500],
BTC: [20000, 15000, 17000]
}
then you can access each one and use Math.max or Math.min to grab the highest / lowest value of that hashmap. E.G. Math.max(coins.BTC)
And if you need to iterate over the coins you have Object.keys:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Thank you all for your answer. I ended up using something like:
leaderboard = []
for (a = 0; a < Object.keys(wallets.data).length; a++) {
if (wallets.data[a].balance.amount > 0) {
leaderboard.push({"currency":wallets.data[a].balance.currency, "price":accprice}) //accprice = variable which contains the value of the userhold coins of the current coin in EUR
}
}
console.log(leaderboard.sort(sort_by('price', true, parseInt)));

Related

Function returning object instead of Array, unable to .Map

I'm parsing an order feed to identify duplicate items bought and group them with a quantity for upload. However, when I try to map the resulting array, it's showing [object Object], which makes me think something's converting the return into an object rather than an array.
The function is as follows:
function compressedOrder (original) {
var compressed = [];
// make a copy of the input array
// first loop goes over every element
for (var i = 0; i < original.length; i++) {
var myCount = 1;
var a = new Object();
// loop over every element in the copy and see if it's the same
for (var w = i+1; w < original.length; w++) {
if (original[w] && original[i]) {
if (original[i].sku == original[w].sku) {
// increase amount of times duplicate is found
myCount++;
delete original[w];
}
}
}
if (original[i]) {
a.sku = original[i].sku;
a.price = original[i].price;
a.qtty = myCount;
compressed.push(a);
}
}
return compressed;
}
And the JS code calling that function is:
contents: compressedOrder(item.lineItems).map(indiv => ({
"id": indiv.sku,
"price": indiv.price,
"quantity": indiv.qtty
}))
The result is:
contents: [ [Object], [Object], [Object], [Object] ]
When I JSON.stringify() the output, I can see that it's pulling the correct info from the function, but I can't figure out how to get the calling function to pull it as an array that can then be mapped rather than as an object.
The correct output, which sits within a much larger feed that gets uploaded, should look like this:
contents:
[{"id":"sku1","price":17.50,"quantity":2},{"id":"sku2","price":27.30,"quantity":3}]
{It's probably something dead simple and obvious, but I've been breaking my head over this (much larger) programme till 4am this morning, so my head's probably not in the right place}
Turns out the code was correct all along, but I was running into a limitation of the console itself. I was able to verify this by simply working with the hard-coded values, and then querying the nested array separately.
Thanks anyway for your help and input everyone.
contents: compressedOrder(item.lineItems).map(indiv => ({
"id": indiv.sku,
"price": indiv.price,
"quantity": indiv.qtty
}))
In the code above the compressedOrder fucntion returns an array of objects where each object has sku, price and qtty attribute.
Further you are using a map on this array and returning an object again which has attributes id, price and quantity.
What do you expect from this.
Not sure what exactly solution you need but I've read your question and the comments, It looks like you need array of arrays as response.
So If I've understood your requirement correctly and you could use lodash then following piece of code might help you:
const _ = require('lodash');
const resp = [{key1:"value1"}, {key2:"value2"}].map(t => _.pairs(t));
console.log(resp);
P.S. It is assumed that compressedOrder response looks like array of objects.

Group by in javascript or angularjs

I just want to do sum value column based on the Year and my data is below, but I don't know how to do this either using angular(in script) or javascript.
[
{"Year":2013,"Product":"A","Value":0},
{"Year":2013,"Product":"B","Value":20},
{"Year":2013,"Product":"A","Value":50},
{"Year":2014,"Product":"D","Value":55},
{"Year":2014,"Product":"M","Value":23},
{"Year":2015,"Product":"D","Value":73},
{"Year":2015,"Product":"A","Value":52},
{"Year":2016,"Product":"B","Value":65},
{"Year":2016,"Product":"A","Value":88}
]
I want to perform the sum on Value column and remove Product column as well.
Thanks
Edit As commenters have pointed out, this doesn't even require Lodash. Been using Lodash so much for current project I forgot reduce is built in. :-)
Also updated to put data in desired form [{"yyyy" : xxxx},...].
This code will accomplish this:
var data = [{"Year":2013,"Product":"A","Value":0},{"Year":2013,"Product":"B","Value":20},{"Year":2013,"Product":"A","Value":50},{"Year":2014,"Product":"D","Value":55},{"Year":2014,"Product":"M","Value":23},{"Year":2015,"Product":"D","Value":73},{"Year":2015,"Product":"A","Value":52},{"Year":2016,"Product":"B","Value":65},{"Year":2016,"Product":"A","Value":88}];
var sum = data.reduce(function(res, product){
if(!(product.Year in res)){
res[product.Year] = product.Value;
}else{
res[product.Year] += product.Value;
}
return res;
}, {});
result = [];
for(year in sum){
var tmp = {};
tmp[year] = sum[year];
result.push(tmp);
}
console.log(result);
RESULT:
[{"2013" : 70}, {"2014" : 78}, {"2015" : 125}, {"2016" : 153}]
ORIGINAL ANSWER
The easiest way I can think of to do this is with the Lodash Library. It gives you some nice functional programming abilities like reduce, which basically applies a function to each element of an array or collection one by one and accumulates the result.
In this case, if you use Lodash, you can accomplish this as follows:
var data = [{"Year":2013,"Product":"A","Value":0},{"Year":2013,"Product":"B","Value":20},{"Year":2013,"Product":"A","Value":50},{"Year":2014,"Product":"D","Value":55},{"Year":2014,"Product":"M","Value":23},{"Year":2015,"Product":"D","Value":73},{"Year":2015,"Product":"A","Value":52},{"Year":2016,"Product":"B","Value":65},{"Year":2016,"Product":"A","Value":88}];
result = _.reduce(data, function(res, product){
if(!(product.Year in res)){
res[product.Year] = product.Value;
}else{
res[product.Year] += product.Value;
}
return res;
}, {});
This yields:
{
"2013": 70,
"2014": 78,
"2015": 125,
"2016": 153
}
Basically, what we're telling Lodash is that we want to go through all the elements in data one by one, performing some operation on each of them. We're going to save the results of this operation in a variable called res. Initially, res is just an empty object because we haven't done anything. As Lodash looks at each element, it checks if that Product's year is in res. If it is, we just add the Value to that year in res. If it's not, we set that Year in res to the Value of the current product. This way we add up all the product values for each year.
If you want to try it out you can do it here:
Online Lodash Tester
Cheers!
You could do this using plain JavaScript. We use an object that will hold the results and the forEach array method. The object that would hold the results would have as keys the years and as values the sums of the corresponding values.
var data = [
{"Year":2013,"Product":"A","Value":0},
{"Year":2013,"Product":"B","Value":20},
{"Year":2013,"Product":"A","Value":50},
{"Year":2014,"Product":"D","Value":55},
{"Year":2014,"Product":"M","Value":23},
{"Year":2015,"Product":"D","Value":73},
{"Year":2015,"Product":"A","Value":52},
{"Year":2016,"Product":"B","Value":65},
{"Year":2016,"Product":"A","Value":88}
];
groupedData = {};
data.forEach(function(item){
var year = item.Year;
var value = item.Value;
if(groupedData.hasOwnProperty(year)){
groupedData[year]+=value;
}else{
groupedData[year]=value;
}
});
console.log(groupedData);

Looping through nesting of objects and arrays with Javascript and underscore

I am trying to access objects that are nested within an array. I start with this JSON object (which was derived from an XML database output):
{"report":
{"date":"15 Apr 2016",
"metrics":
{"metric":
[
{"name":"Bank Angle",
"display_parent_group":"Bankfull",
"display_child_group":"SiteShape",
"tolerance":"0.05",
"visits":
{"visit":
[
{"visit_id":"3047","value": "0.47"},
{"visit_id":"2164","value": "0.55"},
{"visit_id":"1568","value": "0.72"},
{"visit_id":"3431","value": "0.12"},
{"visit_id":"2428","value": "0.44"},
{"visit_id":"1567","value": "0.49"}
]}},
{"name":"Bank Angle SD",
"display_parent_group":"Bankfull",
"display_child_group":"SiteShape",
"tolerance":"0.05",
"visits":
{"visit":
[
{"visit_id":"3047","value": "0.12"},
{"visit_id":"2164","value": "0.05"},
{"visit_id":"1568","value": "0.21"},
{"visit_id":"3431","value": "0.68"},
{"visit_id":"2428","value": "0.22"},
{"visit_id":"1567","value": "0.13"}
]}},
{"name":"Bankfull Area",
"display_parent_group":"Bankfull",
"display_child_group":"SiteSize","tolerance":"0.05",
"visits":
{"visit":
[
{"visit_id":"3047","value": "202"},
{"visit_id":"2164","value": "193"},
{"visit_id":"1568","value": "115"},
{"visit_id":"3431","value": "258"},
{"visit_id":"2428","value": "89"},
{"visit_id":"1567","value": "206"}
]}}
]
}
}
}
I then use underscore to extract a subset of metric objects:
var table_metric = JSONData.report.metrics.metric;
var target_metrics = _.where(table_metric, {
display_parent_group : 'Bankfull', display_child_group: 'SiteShape'
});
This results in an array with two nested objects. Where I'm having a problem is then accessing the array of objects which is nested inside visits.visit. If, for instance, I want to build an array of values associated with the key visit_id, and I try:
function buildVisitIDArray(target_metrics) {
var attrList = [];
for(var i=0; i<target_metrics.length; i++) {
var visit_records = target_metrics[i].visits[1];
console.log(visit_records);
for(visit_record in visit_records) {
attrList.push(_.pluck(visit_record, "visit_id"));
}
}
return attrList
}
I just get an array of undefined results. I've spent hours trying variations on the syntax to get at the nested "visit" objects, but I just can't seem to figure it out.
Any help is much appreciated for this novice!
In your buildVisitIDArray function, you are trying to get target_metrics[i].visits[1] as if it was an array, but it's actually an object, so you should use it this way:
function buildVisitIDArray(target_metrics) {
attrList = [];
for(var i=0; i<target_metrics.length; i++) {
var visit_records = target_metrics[i].visits; // Removed the array call ([1])
console.log(visit_records);
for(visit_record in visit_records) {
attrList.push(_.pluck(visit_records[visit_record], "visit_id"));
}
}
return attrList;
}
Hope it helps :)
You may also have an issue if you're not defining attrList with the var keyword somewhere else in your code.
Building on Andre's answer, you may want to change this line to be:
visit_records = target_metrics[i].visits.visit;
to go one layer deeper, then do a regular array for loop afterward.

Sorting specific structure objects by their properties

So I have such dummy data object:
var Products = {
'sku': {n:'Trampolines rain covers',v:'7Ft',l:'http://www.google.com',i:['media/cache/search/media/1151-Trampoline-jumping-mat.png','media/cache/searchSuggest/media/1151-Trampoline-jumping-mat.png','#'],r:['4','3.2','0','1','3','0','0'],p:['7.99','9.99'],d:'Some kind of description',f:'Features',b:'Benefits',s:'Specifications'},
'sku2': {n:'Icon cast adjustable dumbbell',v:'10kg',l:'http://www.google.com',i:['media/cache/search/media/1167-Single-dumbbell.png','media/cache/searchSuggest/media/1167-Single-dumbbell.png','#'],r:['4','2.5','1','0','1','0','2'],p:['7.99','9.99'],d:'Some kind of description',f:'Features',b:'Benefits',s:'Specifications'},
'sku3': {n:'Trampolines safety net & bases',v:'6Ft',l:'http://www.google.com',i:['media/cache/search/media/1195-Trampoline-safety-net.png','media/cache/searchSuggest/media/1195-Trampoline-safety-net.png','#'],r:['3','3.5','1','0','1','0','1'],p:['7.99','9.99'],d:'Some kind of description',f:'Features',b:'Benefits',s:'Specifications'},
'sku4': {n:'Andico spring for trampolines',v:'5.5 inch',l:'http://www.google.com',i:['media/cache/search/media/1166-Trampoline.png','media/cache/searchSuggest/media/1166-Trampoline.png','#'],r:['3','3.5','1','0','1','0','1'],p:['7.99','9.99'],d:'Some kind of description',f:'Features',b:'Benefits',s:'Specifications'}
}
and then I have array of skus
var skus = ['sku','sku3','sku4'];
My task is to sort this array by sku object property n (which is string / product title of multi words) alphabetically ascending.
I know for that I should use .sort(ref) function, but I wonder with function inside, something like:
skus.sort(function(a,b) { });
But I can't find out how to formulate the inner function to make the job done. Maybe I should do this in another way?
You're very nearly there. Within the function, you use a and b to look up the entries on your Products object, so you can compare entries:
skus.sort(function(a, b) {
var an = Products[a].n,
bn = Products[b].n;
if (an === bn) {
return 0;
}
return an < bn ? -1 : 1;
});

How to sort a set of XML results based on bid value?

I'm probably missing missing something real simple here.
I've an XML feed. I know how to parse the XML itself, but how do I turn, say, an array of objects like:
[
{bid:"0.001", title:'test title', description:'test description'},
{bid:"0.025", title:'why are you', description:'still reading'}
]
..into an array where I know that array[0] will fetch me the XML result object with the highest bid - meaning, I need to scan through the objects inside and sort them by highest bid.
I've messed around with jquery's filter but I can't get it to work.
Sort an array using custom sorting function:
your_array.sort(sortByBid);
sortByBid = function(a, b) {
var a_bid = parseFloat(a.bid);
var b_bid = parseFloat(b.bid);
if (a_bid === b_bid) {
return 0;
}
return (a_bid > b_bid ? 1 : -1);
}

Categories

Resources