我有两个数组,根据元素在数组中的位置,它会收到一个值。两个数组都包含相同的元素,但位于不同的位置。我想计算每个元素的值,将数组合并到一个数组中,然后对新数组进行排序。
我能想到的唯一想法是将我的初始数组转换为对象数组,合并它们,按对象值排序,然后将该顺序映射到新数组中。
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']
答案 0 :(得分:2)
你可以跳过带有对象的新临时数组的部分,只取一个对象进行计数,然后取出排序的键作为结果。
var array1 = ['aaa', 'bbb', 'ddd', 'eee', 'ccc'],
array2 = ['ddd', 'ccc', 'aaa', 'bbb', 'eee'],
temp = Object.create(null),
result;
[array1, array2].forEach(a => a.forEach((k, i) => temp[k] = (temp[k] || 0) - i));
result = Object.keys(temp).sort((a, b) => temp[b] - temp[a]);
console.log(result);
&#13;
答案 1 :(得分:1)
您可以使用reduce
创建对象,然后在sort
上使用Object.keys
。
const array1 = ['aaa', 'bbb', 'ddd', 'eee', 'ccc'];
const array2 = ['ddd', 'ccc', 'aaa', 'bbb', 'eee'];
const n = array1.length;
const r = array1.reduce((r, e, i) => (r[e] = n - i + n - array2.indexOf(e), r), {})
const result = Object.keys(r).sort((a, b) => r[b] - r[a])
console.log(result)
&#13;