I am faced with a challenge of working with two arrays where each element receives a value based on its position within the array. Although both arrays contain the same elements, they are arranged differently. My goal is to calculate the value for each element, merge the arrays into one, and then sort the combined array.
One approach I have in mind involves converting the initial arrays into arrays of objects, merging them, sorting by object value, and then mapping that order into a new array.
var ranks = [],
objArray1 = [],
objArray2 = [];
// 'aaa' = 5, 'bbb' = 4, 'ddd' = 3, 'eee' = 2, 'ccc' = 1
var array1 = ['aaa', 'bbb', 'ddd', 'eee', 'ccc'];
// 'ddd' = 5, 'ccc' = 4, 'aaa' = 3, 'bbb' = 2, 'eee' = 1
var array2 = ['ddd', 'ccc', 'aaa', 'bbb', 'eee'];
for (var i = 0, x = 5; i < 5; x--, i++) {
var obj = {};
obj[array1[i]] = x;
objArray1.push(obj);
}
for (var i = 0, x = 5; i < 5; x--, i++) {
var obj = {};
obj[array2[i]] = x;
objArray2.push(obj);
}
// combine both object arrays, match keys, but add values
// should output ranks =[{aaa: 8}, {bbb: 6}, {ccc: 5}, {ddd: 8}, {eee: 3}]
// then sort based on value
// should output ranks = [{aaa: 8}, {ddd: 8}, {bbb: 6}, {ccc: 5}, {eee: 3}]
// then copy keys over to new array while keeping position
// should output var final = ['aaa', 'ddd', 'bbb', 'ccc', 'eee']