1

How to sort array of objects by property 'cost' with holding string keys?

Start array :

aparts: {
    apart1 : {id: "1", status: 2, cost: 10033450},
    apart2 : {id: "2", status: 2, cost: 5214000},
    apart3 : {id: "3", status: 2, cost: 7314300},
    apart4 : {id: "4", status: 1, cost: 9261700}    
}

Want to array:

aparts: {
    apart2 : {id: "2", status: 2, cost: 5214000},
    apart3 : {id: "3", status: 2, cost: 7314300},
    apart4 : {id: "4", status: 1, cost: 9261700},
    apart1 : {id: "1", status: 2, cost: 10033450}   
}
krolovolk
  • 464
  • 6
  • 18

3 Answers3

2

The order of properties is not guaranteed. See, for example here:

https://stackoverflow.com/a/5525820/1250301

If you want something ordered, then you need to use an array. The transformation is pretty straightforward:

var aparts = {
    apart1 : {id: "1", status: 2, cost: 10033450},
    apart2 : {id: "2", status: 2, cost: 5214000},
    apart3 : {id: "3", status: 2, cost: 7314300},
    apart4 : {id: "4", status: 1, cost: 9261700}    
};

var arr = Object.keys(aparts).map(function(k) { return aparts[k]; }).sort(function(a,b) { return a.cost - b.cost });

console.log(arr);
Matt Burland
  • 44,552
  • 18
  • 99
  • 171
1

const aparts = {
    apart1: {id:"1", status: 2, cost: 10033450},
    apart2: {id:"2", status: 2, cost: 5214000},
    apart3: {id:"3", status: 2, cost: 7314300},
    apart4: {id:"4", status: 1, cost: 9261700}    
};

const arr = 
  Object.keys(aparts)
  .map(k => (aparts[k]))
  .sort((a,b) => (a.cost - b.cost))
  .map(k => ({["apart" + k.id]: k}))
;

console.log(arr);
Milan Rakos
  • 1,705
  • 17
  • 24
0

I believe you are looking for a Map. Which is what your irregular object matches.

let aparts= {
    apart1: { id: "1", status: 2, cost: 10033450 },
    apart2: { id: "2", status: 2, cost: 5214000 },
    apart3: { id: "3", status: 2, cost: 7314300 },
    apart4: { id: "4", status: 1, cost: 9261700 }
};
let sorted = Object.entries(aparts).map(x => Object.assign(x[1], {
  apart: x[0]
})).sort((a, b) => a.cost - b.cost);

let result = new Map(sorted.map(x => ([x.apart, (delete x.apart, x)])));

console.log(...result)
Rick
  • 1,035
  • 10
  • 18