Home > OS >  Rearrange/order array based on it's object values added together
Rearrange/order array based on it's object values added together

Time:10-25

I've got an array of multiple objects which have 4 key-value (could have more) pairs and an identifier. Is there a way to change order of the array - ascending/descending, based on what Val1, Val2, Val3, Val4 add up?

const array = [
{
 'Val1': 10,
 'Val2': 20,
 'Val3': 30,
 'Val4': 40 , // Val1   Val2   Val3   Val4 = 100 
 'identifier': 'Column1'
},
{
 'Val1': 20,
 'Val2': 30,
 'Val3': 40,
 'Val4': 50, // Val1   Val2   Val3   Val4 = 140 
 'identifier': 'Column2' 
}
]

In this example, let's say I want to change the array to descending order and expected result would be -

const array = [
{
 'Val1': 20,
 'Val2': 30,
 'Val3': 40,
 'Val4': 50, // Val1   Val2   Val3   Val4 = 140 
 'identifier': 'Column2' 
}
{
 'Val1': 10,
 'Val2': 20,
 'Val3': 30,
 'Val4': 40, // Val1   Val2   Val3   Val4 = 100 
 'identifier': 'Column1'
}
]

CodePudding user response:

You can use Array.sort -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

In your case you just need to add them up and subtract. If you do a-b, this will give you an ascending ordering. So for descending, you just need b-a.

eg.

const array = [{"Val1":10,"Val2":20,"Val3":30,"Val4":40,"identifier":"Column1"},{"Val1":20,"Val2":30,"Val3":40,"Val4":50,"identifier":"Column2"}];

array.sort((a,b) => 
    b.Val1   b.Val2   b.Val3   b.Val4
  - a.Val1 - a.Val2 - a.Val3 - a.Val4
);
  
console.log(array);

CodePudding user response:

const array = [
{
 'Val1': 10,
 'Val2': 20,
 'Val3': 30,
 'Val4': 40 , // Val1   Val2   Val3   Val4 = 100 
 'identifier': 'Column1'
},
{
 'Val1': 20,
 'Val2': 30,
 'Val3': 40,
 'Val4': 70, // Val1   Val2   Val3   Val4 = 160 
 'identifier': 'Column3' 
},
{
 'Val1': 20,
 'Val2': 30,
 'Val3': 40,
 'Val4': 50, // Val1   Val2   Val3   Val4 = 140 
 'identifier': 'Column2' 
}], sum=a=>a.Val1 a.Val2 a.Val3 a.Val4;

console.log("ascending",array.sort((a,b)=>sum(a)-sum(b)));
console.log("descending",array.sort((a,b)=>sum(a)-sum(b)));

CodePudding user response:

You can't just sort object, as different engines will show your object differently. For example, sorted object in V8 and SpiderMonkey someday will compile differently.

So, the robust solution is to turn your data into an array. You should never make assumptions about the order of elements in a JavaScript object.

  • Related