javascriptnode.jsarrays

Best way to re arrange array of object?


I have an array or object which will serve as columns for a table with a unique key

const list = [{
    key: "Name",
    textColor: "red"
  },{
    key: "Age",
    textColor: "green"
  },{
    key: "Occupation",
    textColor: "yellow"
}]

And, I have a list of ordering of columns in the table

const newOrder = ["Occupation", "Name", "Age"]

Now , how can i rearrange the list according to the newOrder without using nested loops. Also, these all are dynamic, so it's not just about the above mentioned three columns.

Expected output:

const list = [{
    key: "Occupation",
    textColor: "yellow"
  },{
    key: "Name",
    textColor: "red"
  },{
    key: "Age",
    textColor: "green"
}]

Solution

  • Your list can be reformatted to a regular javascript object in which key is the property name, and textColor is the value:

    const toObject = kvps => Object.fromEntries(kvps.map(kvp => [ kvp.key, kvp.textColor ]));
    

    With a given array of keys, you can pick values from that object like so:

    const fromObject = (order, obj) => order.map(key => ({ key, textColor: obj[key] }));
    

    Chain the two together, and you can reorder any list of key value pairs:

    const list = [{
        key: "Name",
        textColor: "red"
      },{
        key: "Age",
        textColor: "green"
      },{
        key: "Occupation",
        textColor: "yellow"
    }]
    
    
    const toObject = kvps => Object.fromEntries(kvps.map(kvp => [ kvp.key, kvp.textColor ]));
    const fromObject = (order, obj) => order.map(key => ({ key, textColor: obj[key] }));
    const reorder = (order, kvps) => fromObject(order, toObject(kvps));
    
    
    const newList = reorder(["Occupation", "Name", "Age"], list);
    
    console.log(
      newList
    )

    Edit: if the sizes of your list and order arrays are small, you probably want to go with the much easier to read approach suggested by Jon Webb in one of the other answers. 🙂 I tried to keep my solution to an O(n + m) complexity rather than O(n * m), (n = list size, m = order size) but it's probably not worth the added complexity.