I have this function below to sort the keys of an object accordly their values.
var obj = {"A": 50, "B": 10, "C": 150 };
var ordered = Object.keys(obj).sort(function(a,b) {
return obj[a] > obj[b] ? -1 :
obj[b] > obj[a] ? 1 : 0;
});
console.log(ordered); // => [C, A, B];
However, when I have an Array of Objects, this function returns nothing.
For an Array of objects like this below:
var objs = [
{"A": 50, "B": 10, "C": 150 },
{"A": 60, "B": 100, "C": 10 },
{"A": 150, "B": 100, "C": 30 }
]
I have tried something like this:
let op =[];
objs.forEach((obj) => {
let ordered = {};
Object.keys(obj).sort().forEach((a,b) => {
ordered = obj[a] > obj[b] ? -1 : obj[b] > obj[a] ? 1 : 0;
});
op.push(ordered);
});
console.log(op);
But this function returns an error: Identifier 'op' has already been declared.
I need to return something similar to the example above, but applied to each object. The result would be:
console.log(ordered); // => [[C, A, B], [B, A, C], [A, B, C]]
Identifier 'op' has already been declared.You've only declaredoponce in the code you posted, though...let opline. You could also wrap it in a block.