合并并排序Javascript中的两个对象数组

合并并排序Javascript中的两个对象数组

本文介绍了合并并排序Javascript中的两个对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组,根据元素在数组中的位置,它会接收一个值.两个数组都包含相同的元素,但位置不同.我想计算每个元素的值,将数组合并为一个数组,然后对新数组进行排序.

I have two arrays and depending on the element's position in the array it receives a value. Both arrays contain the same elements, but at different positions. I would like to calculate the value for each element, merge the arrays into a single array, and sort the new array.

我能想到的唯一想法是将初始数组转换为对象数组,合并对象,按对象值排序,然后将顺序映射到新数组中.

The only idea I can think of is to turn my initial arrays into arrays of objects, merge those, sort by object value, then map 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']

推荐答案

您可以跳过带有新的带有对象的临时数组的部分,而只取一个对象进行计数,然后将排序后的键作为结果.

You could skip the part with new temporary arrays with objects and take just an object for counting and then take the sorted keys as result.

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

这篇关于合并并排序Javascript中的两个对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:07