如何使用基本数组对象对名称/值对对象数组进行排序

时间:2018-10-30 08:12:20

标签: javascript arrays node.js

我的主数组为

var emaillist = [{"name":"harish","value":"varma"},
                 {"name":"ram","value":"john"},
                 {"name":"dam","value":"sam"},
            {"name":"james","value":"hope"}]

我还有另一个Modifyedemaillist数组,其值将与上面的数组相同,但名称将不同

var modifiedemaillist =[{"name":"sam","value":"hope"},
          {"name":"hammy","value":"varma"}, 
             {"name":"nick","value":"john"}]

但是在第二个数组中,与第二个数组相比,对象不是按顺序排列的。

使用电子邮件列表数组基于值对第二个数组进行排序最简单的方法是什么,因为这两种方法都很常见。

我的修改后的电子邮件列表应为

[{"name":"hammy","value":"varma"},
 {"name":"nick","value":"john"}, 
 {"name":"sam","value":"hope"}]

有人可以帮忙吗!

4 个答案:

答案 0 :(得分:0)

使用.mapemaillist转换成仅包含value的数组,然后通过比较{{ 1}}中该有序数组中的每个项目:

.sort

另一个性能更高的选项是,创建一个modifiedemaillist而不是indexOf,其键是var emaillist = [{"name":"harish","value":"varma"}, {"name":"ram","value":"john"}, {"name":"dam","value":"sam"}, {"name":"james","value":"hope"}]; var values = emaillist.map(({ value }) => value); var modifiedemaillist = [{"name":"sam","value":"hope"}, {"name":"hammy","value":"varma"}, {"name":"nick","value":"john"}]; modifiedemaillist.sort( (a, b) => values.indexOf(a.value) - values.indexOf(b.value) ); console.log(modifiedemaillist);,其值是该项目在其中的索引原始数组。这会有所帮助,因为.map的查找时间通常为Map,而value的查找时间为Map.get

O(1)

答案 1 :(得分:0)

您需要基于value属性在第一个数组中找到对象的索引,以对第二个数组进行排序:

var emaillist = [{
    "name": "harish",
    "value": "varma"
  },
  {
    "name": "ram",
    "value": "john"
  },
  {
    "name": "dam",
    "value": "sam"
  },
  {
    "name": "james",
    "value": "hope"
  }
];

var modifiedemaillist = [{
    "name": "sam",
    "value": "hope"
  },
  {
    "name": "hammy",
    "value": "varma"
  },
  {
    "name": "nick",
    "value": "john"
  }
];

modifiedemaillist.sort(function(a, b){
  var indexA = emaillist.findIndex(({value}) => value === a.value);
  var indexb = emaillist.findIndex(({value}) => value === b.value);
  return indexA - indexb;
});
console.log(modifiedemaillist);

答案 2 :(得分:0)

您可以存储值的索引,并将inidces的差值作为排序值。

对于未知的value,您可以将Infinity作为默认值,并将递增的索引值作为映射值(以防止零触发默认值)。

var emaillist = [{ name: "harish", value: "varma" }, { name: "ram", value: "john" }, { name: "dam", value: "sam" }, { name: "james", value: "hope" }],
    modifiedemaillist = [{ value: "unknown1" }, { name: "sam", value: "hope" }, { value: "unknown2" }, { name: "hammy", value: "varma" }, { name: "nick", value: "john" }],
    order = emaillist.reduce((m, { value }, i) => m.set(value, i + 1), new Map);
             
modifiedemaillist.sort(({ value: a }, { value: b }) => (order.get(a) || Infinity) - (order.get(b) || Infinity));

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

答案 3 :(得分:0)

最简单的方法是遍历源数组并推送到第二个数组包含的结果值,然后添加其余值

date = '30-10-2018'