While attempting to organize an array of objects in descending order using pure javascript, I encountered a challenge. Initially, I suspected that the issue might be related to the JSON.stringify method, as discussed [here][1]. It turned out that JSON.stringify does not maintain the order of objects intentionally. When sorting the array of objects and then accessing the weight property of the first object in the array, I noticed that I would sometimes get a weight value of .29 or .35. Here is the code snippet I used:
var byWeight = objArray.slice(0);
var sorted = byWeight.sort(function(a,b) { return b.weight - a.weight; } );
sorted[0].something.weight;
Upon running this code multiple times, the weight value appeared to be randomly either .29 or .35. Can you explain why this inconsistency is happening?
Below is the array being processed:
[
{
"something": {
"terms": [
{
"elements": {
"number": {
"span": [
9,
10
],
"value": "1"
}
},
"span": [
9,
12
],
"value": "1g",
"label": "grams"
}
],
"span": [
9,
12
],
"weight": 0.29,
"value": "1gm"
}
},
{
"something": {
"terms": [
{
"elements": {
"number": {
"span": [
16,
18
],
"value": "30"
}
},
"span": [
16,
20
],
"value": "30ml",
"label": "liters"
}
],
"span": [
16,
20
],
"weight": 0.35,
"value": "30ml"
}
}
]