0

I am creating an app with angularjs which receives data from 2 api's and creates a chart with smart-table for cryptocurrency data.

I am currently stuck on trying to sort the data in my table using smart-table beacuse the data i recieve from the JSON is string type ( value, % change , and so on)

Here is an example of the JSON that I want to convert certain objects to string type (value,change,rank...) json file

How can i convert certain objects in my JSON to be numbers instead of string so smart-table sorting will work properly. It currently sees all the values as strings and sorts as follows:

9999$
9$
889% 

picture example

Kasia Gogolek
  • 3,374
  • 4
  • 33
  • 50
user1451752
  • 1
  • 1
  • 1
  • Possible duplicate of [What's the best way to convert a number to a string in JavaScript?](https://stackoverflow.com/questions/5765398/whats-the-best-way-to-convert-a-number-to-a-string-in-javascript) – Heretic Monkey Feb 09 '18 at 15:15

2 Answers2

0

A simple for loop which converts string to a Number and reassigns it to json.

for(var i = 0; i < json.length; i++){
   json.price_usd = Number(json.price_usd);
}

And as Aleksey states, here's a one liner you can also use...

json.forEach((x)=>{ x.price_usd=Number(x.price_usd) });
Adrian
  • 8,271
  • 2
  • 26
  • 43
  • One-liner: `json.forEach((x)=>{x.price_usd=Number(x.price_usd.replace("$",""))})` (`$` logic can be removed) – Aleksey Solovey Feb 09 '18 at 14:43
  • If OP doesn't know how to perform such simple task, I don't think your one liner is of any use other than more confusion to him. Also price doesn't contain a `$` symbol in the data set provided. – Adrian Feb 09 '18 at 14:45
  • yes it doesnt contain the $ symbol i added that to the expression, true that i dont know to use es6 yet :) been programming for 2 months now xD. ty so much for your answer adriani6 couldnt believe it would be so simple , i was thinking about parseFloat or something like a map function to change the entire array. ill try out your answer now ty again m8. – user1451752 Feb 09 '18 at 16:12
0

Try using parseInt and parseFloat functions :

var number1 = parseInt("10");
var number2 = parseFloat("10.20");

A simple Example :

//array variable
var array=[
  {"rank":"63", "value":"98.2$"},
       {"rank":"2","value":"831.38$"},
       {"rank":"9","value":"8.58$"}];

//Convert string to number
array.forEach(function(elem){
  elem.rank=parseInt(elem.rank);
  elem.value=parseFloat(elem.value);
  console.log("Rank:"+elem.rank+" - Value:"+elem.value);
});

//sort by the 'value'
array.sort(function(a,b) {
  if (a.value < b.value)
    return -1;
  if (a.value > b.value)
    return 1;
  return 0;
});

console.log("*** Result after sorting ***");
//print the result
array.forEach(function(elem){
    console.log("Rank:"+elem.rank+" - Value:"+elem.value);
});
iLyas
  • 1,047
  • 2
  • 13
  • 30