skip to Main Content

I wanna sort object fields for iterated array index.
For example:

const data = {
                "all": 2,
                "test1": 0,
                "test": 2,
                "test2": 0,
                "test3": 0,
                "test4": 0,
                "test5": 0
            };
const users = [ "test","test1","test2","test3","test4","test5"];

I wanna data object like this:

data = {
                    "all": 2,
                    "test": 2,
                    "test1": 0,
                    "test2": 0,
                    "test3": 0,
                    "test4": 0,
                    "test5": 0
}

How can i achieve this?

2

Answers


  1. You can sort the entries of the object based on the index of the key in the array.

    const data = {
      "all": 2,
      "test1": 0,
      "test": 2,
      "test2": 0,
      "test3": 0,
      "test4": 0,
      "test5": 0
    };
    const users = ["test", "test1", "test2", "test3", "test4", "test5"];
    let res = Object.fromEntries(Object.entries(data).sort(([k1], [k2]) => 
                users.indexOf(k1) - users.indexOf(k2)));
    console.log(res);
    Login or Signup to reply.
  2. A similar question has been answered here.

    const data = {
      "all": 2,
      "test1": 0,
      "test": 2,
      "test2": 0,
      "test3": 0,
      "test4": 0,
      "test5": 0
    };
    
    const sortable = Object.entries(data).sort(([,a],[,b]) => b-a).reduce((r, [k, v]) => ({ ...r, [k]: v }), {});
    
    console.log(sortable);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search