如何根据另一个重新排列数组?

时间:2016-12-02 14:28:46

标签: javascript

在我在D3.js中的可视化中,我有一个初始数组。它按照从最小到最大的值进行排序。

var firstDataset = [
  {place: "fifth", category: "A", value: 100},
  {place: "sixth", category: "C", value: 200},
  {place: "fourth", category: "B", value: 300},
  {place: "third", category: "B", value: 400},
  {place: "first", category: "A", value: 500},
  {place: "second", category: "C", value: 600}
];

我还有另一个数组。它已根据属性“类别”从A到C进行排序。

var secondDataset = [
  {place: "first", category: "A", value: 1500},
  {place: "fifth", category: "A", value: 6500},
  {place: "third", category: "B", value: 3500},
  {place: "fourth", category: "B", value: 5500},
  {place: "second", category: "C", value: 2500},
  {place: "sixth", category: "C", value: 4500}
];

属性“place”和“category”在两种情况下都相同。价值观不同。如何重新排列第二个数组以获得第一个数组中的元素序列?

1 个答案:

答案 0 :(得分:4)

您可以使用placecategory属性作为带对象的排序顺序的键,这反映了所需的顺序。



var firstDataset = [{ place: "fifth", category: "A", value: 100 }, { place: "sixth", category: "C", value: 200 }, { place: "fourth", category: "B", value: 300 }, { place: "third", category: "B", value: 400 }, { place: "first", category: "A", value: 500 }, { place: "second", category: "C", value: 600 }],
    secondDataset = [{ place: "first", category: "A", value: 1500 }, { place: "fifth", category: "A", value: 6500 }, { place: "third", category: "B", value: 3500 }, { place: "fourth", category: "B", value: 5500 }, { place: "second", category: "C", value: 2500 }, { place: "sixth", category: "C", value: 4500 }],
    getKey = function (o) { return o.place + '|' + o.category; },
    order = Object.create(null);

firstDataset.forEach(function (o, i) {
    order[getKey(o)] = i;
});

secondDataset.sort(function (a, b) {
    return order[getKey(a)] - order[getKey(b)];
});

console.log(secondDataset);

.as-console-wrapper { max-height: 100% !important; top: 0; }