JavaScript: Array + Object to Sorted Array

Have been stuck on this issue for 6+ hours. I have started to learn JavaScript few months ago, so far so good, but cant resolve this one.

const arrHeader["name","street","city","state","zip","phone","fax","custom"];

object as follows

const obj = {
      zip: "01001"
      phone: "77894644"
      city: "Albany",
      state: NY,
      name: "John",
      street: "123 Main St"
      custom: "best user"
      fax: ""
    };

It is possible to get output as array (not associated array/object) sorted based on arrHeader? the lengh of array/object is the same. Please note blank for fax, the index in result should correspond to arrHeader, even if the value is null. Than you. Any suggestion are appreciated.

Output should look like for the given object. Not sure if ” ” best to keep index same.

var result["John","123 Main St","Albany","NY","01001","77894644"," ","best user"];

Thank you.

Answer

Please find Array.reduce implementation of your requirement.

const arrHeader = ["name","street","city","state","zip","phone","fax","custom"];
const obj = {
  zip: "01001",
  phone: "77894644",
  city: "Albany",
  state: "NY",
  name: "John",
  street: "123 Main St",
  custom: "best user",
  fax: ""
};
const result = arrHeader.reduce((acc, curr) => {
  acc.push(obj[curr]);
  return acc;
}, []);
console.log(result);

Array.map implementation

const arrHeader = ["name","street","city","state","zip","phone","fax","custom"];
const obj = {
  zip: "01001",
  phone: "77894644",
  city: "Albany",
  state: "NY",
  name: "John",
  street: "123 Main St",
  custom: "best user",
  fax: ""
};
const result = arrHeader.map((node) => obj[node])
console.log(result);