how to sort object properties in javascript code example

Example 1: sort by object property javascript

let list = [
  {
      name: "world"
  },
  {
      name: "hello",
  },
];

// This doesn't account for if names are the same between objects
let x = list.sort((a, b) => (a.name > b.name ? 1 : -1));

console.log(x);

/*
[
  {
      name: "hello",
  },
  {
      name: "world"
  },
];
*/

Example 2: javascript sort object

var maxSpeed = {
    car: 300, 
    bike: 60, 
    motorbike: 200, 
    airplane: 1000,
    helicopter: 400, 
    rocket: 28800
};
var sortable = [];
for (var vehicle in maxSpeed) {
    sortable.push([vehicle, maxSpeed[vehicle]]);
}

sortable.sort(function(a, b) {
    return a[1] - b[1];
});

//[["bike", 60], ["motorbike", 200], ["car", 300],
//["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]

Example 3: hange the order of properties in object javascript

// Method 1: Returnes new Object
function preferredOrder(obj, order) {
  // returns new object with modified keys
     const newObj: any = {};
        for (let key of order) {
            newObj[key] = obj[key];
        }
       return newObj;
}

// Method 2: Modifies that Object
 preferredOrder(obj: any, keyOrder: any[]) {
        // modifies old object with new order
        keyOrder.forEach((k) => {
            const v = obj[k]
            delete obj[k]
            obj[k] = v
        })
    }


// preferredOrder({a:'a',b:'b',c:'c'},[b,a,c])
// output= >  {b:'b',a:'a',c:'c'}

Tags:

Cpp Example