-1

How can I sort the items by price? It wont work if I run like this sortData('price'), it will work only if I change obj1.type to obj1.price, but I dont want to write duplicate function just because of the key.

   function sortData(type) {
        var items = [{id:3,price:40}, {id:5,price:100}, {id:1,price:1}];
        items.sort(function(obj1,obj2) {
            return obj1.type - obj2.type;   
        })
    }
vbnewbie
  • 206
  • 6
  • 26

2 Answers2

1

Check this solution, i hope it will help you :D

function sortData(type) {
        var items = [{id:3,price:40}, {id:5,price:100}, {id:1,price:1}];
        items.sort(function(obj1,obj2) {
            return (obj1[type] - obj2[type]);   
        })
        console.log(items)
    }
  sortData('price');
Akhil Aravind
  • 5,741
  • 16
  • 35
0

You could take a function which returns a function for the callback by using a closure over the key.

function sortBy(key) {
    return function (a, b) {
        return a[key] - b[key];
    };
}

var items = [{ id: 3, price: 40 }, { id: 5, price: 100 }, { id: 1, price: 1 }];

items.sort(sortBy('price'));
console.log(items);

items.sort(sortBy('id'));
console.log(items);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392