1

I have an array with correct order line:

let arr1 = ['name', 'age', 'occupation', 'address']

and I have an another array which is coming from the backend with unsorted format

let arr2 = [{'age': 20, 'address': '', 'occupation': 'student', 'name': 'student name1'}, {'age': 21, 'address': '', 'occupation': 'student', 'name': 'student name2'}, {'age': 22, 'address': '', 'occupation': 'student', 'name': 'student name3'}]

So I need this arr2 objects keys to be sorted the way arr1 keys index positions.

Final output needed:

let arr2Sorted = [{ 'name': 'student name1', 'age': 20, 'occupation': 'student', 'address': ''}, { 'name': 'student name2', 'age': 21, 'occupation': 'student', 'address': ''}, { 'name': 'student name3', 'age': 22, 'occupation': 'student', 'address': ''}]

What I tried:

const arrayMap = arr2.reduce(
      (accumulator, currentValue) => ({
         ...accumulator,
         [currentValue]: currentValue,
      }),
     {},
    );

const result = arr1.map((key) => arrayMap[key]);
4
  • 1
    It is not so easy to enforce the order of the keys in a JavaScript object. Moreover order is generally not important when dealing with key -> values. Why do you need this? Commented Oct 20, 2022 at 15:17
  • the arr1 is client side array that I use this to render table headers, so the key name is the first table column, followed by other keys in the arr1 order, but arr2 that's coming from backend with that order to make it re-usable and dynamic rendering, I need to sort it, to reuse this same table in multiple modules Commented Oct 20, 2022 at 15:20
  • let arr1 = ['name', 'age', 'occupation', 'address'] is not really "sorted" but more on the line of "ordered" since I fail to see any "sort" that would produce that order Commented Oct 20, 2022 at 15:23
  • Your question reads like "How can I do X by using Z" rather than "How can I best do X" Commented Oct 20, 2022 at 16:25

2 Answers 2

2

let arr1 = ['name', 'age', 'occupation', 'address'];
let arr2 = [{'age': 20, 'address': '', 'occupation': 'student', 'name': 'student name1'}, {'age': 21, 'address': '', 'occupation': 'student', 'name': 'student name2'}, {'age': 22, 'address': '', 'occupation': 'student', 'name': 'student name3'}];

let arr3 = arr2.map(i=>Object.fromEntries(arr1.map(p=>[p,i[p]])));

console.log(arr3);

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I never though of using Object.fromEntries for this, it's good
Pretty good compact code answer here.
1

Here I show why it is probably not needed to order the properties, but just use them. I also answer the "How To" in a verbose way.

let arr1 = ['name', 'age', 'occupation', 'address'];
let arr2 = [{
  'age': 20,
  'address': '',
  'occupation': 'student',
  'name': 'student name1'
}, {
  'age': 21,
  'address': '',
  'occupation': 'student',
  'name': 'student name2'
}, {
  'age': 22,
  'address': '',
  'occupation': 'student',
  'name': 'student name3'
}];
// show it is not needed to order props, just use them
const container = document.getElementById("container");
arr2.forEach((el) => {
  arr1.forEach((nm) => {
    const newtext = document.createTextNode(nm + ":" + el[nm]);
    let dv = document.createElement('div');
    dv.appendChild(newtext);
    container.appendChild(dv);
  });
});

// now show how we an order the props - a number of ways to do this
// this is a super verbose way for clarity
let arrPropsOrdered = [];
arr2.forEach((el, index, array) => {
  // console.log("PropName:",arr1[0]);
  // console.log("Object:",el);
  // console.log("ObjectNameProp:",el[arr1[0]]);
  let x = {};
  /* manual way
  x[arr1[0]] = el[arr1[0]];
  x[arr1[1]] = el[arr1[1]];
  x[arr1[2]] = el[arr1[2]];
  x[arr1[3]] = el[arr1[3]];
  */
  // in a loop
  arr1.forEach((nm) => {
    x[nm] = el[nm];
  });
 // console.log("X:", x);
  arrPropsOrdered.push(x);
  // show it pushed in there using the current index
 // console.log("PropsByPropName:", arrPropsOrdered[index]);
});

// console.log(arrPropsOrdered);
<div id="container"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.