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]);
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