I have two arrays: one with the correct order of keys and values, and another array coming from a backend in an unsorted format.
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'}]
The goal is to sort the keys of the second array based on the order of keys in the first array.
Desired final output:
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': ''}]
This is how I attempted to achieve it:
const arrayMap = arr2.reduce(
(accumulator, currentValue) => ({
...accumulator,
[currentValue]: currentValue,
}),
{},
);
const result = arr1.map((key) => arrayMap[key]);