0

Hey I have an object as

data = { vaibhavs:243 "132" , 
         vaibhavs:918 "342", 
         karthikp:265 "345",
         marimuthu:848 "asjkd",
         ushas:918 "sdf15",
         apoorvg:728 "wddfs"....
       }

I need to sort it on the basis of key ,i.e., "vaibhavs:243" alphabatically. I have written the following code for it. I am able to sort the keys, but not able to put it back in the returning object. Please guide what to do.

function sortData(data) {
    var sorted = [];
    Object.keys(data).sort(function (a, b) {
        return a < b ? -1 : 1
    }).forEach(function (key) {
        var obj = {};
        obj[key] = data[key]
        sorted.push(obj);
    });
    return sorted;
}

This is giving me an array of object which i don't want. I want a single object. I can't do this using an array because I need the sorted key-value pairs.

If I am using the following code,

function sortData(data) {
        var sorted = {};
        Object.keys(data).sort(function (a, b) {
            return a < b ? -1 : 1
        }).forEach(function (key) {
            sorted[key] = key[data]
        });
        return sorted;
    }

The above code is always overwriting the existing value. Can someone suggest me how to add the Key value pair. As I have that in sorted order, but just unable to add them in a single object.

Vaibhav Sah
  • 142
  • 1
  • 10
  • 1
    Alert! `Invalid Object` – Tushar Oct 07 '15 at 09:31
  • 2
    you cannot sort an object. Use an array instead. – Tarun Dugar Oct 07 '15 at 09:32
  • I need an object bro because I need key value pair in sorted order. Any other suggestion – Vaibhav Sah Oct 07 '15 at 09:35
  • Use an array that contains objects, since you can't sort properties of an object. Most implementations will either show the properties alphabetically or in order of property declaration: `data = [{vaibhavs:"243 132"},{vaibhavs:"918 342"},{karthikp:"265 345"},{marimuthu:"848 asjkd"},{ushas:"918 sdf15"},{apoorvg:"728 wddfs"}];` You can sort this array now using object.keys on each object. – Shilly Oct 07 '15 at 09:38
  • Hey Shilly.. How to access the keys and values here. I have got the sorted sequences but unable to access values – Vaibhav Sah Oct 07 '15 at 10:05

0 Answers0