在Javascript中提取最大的对象数组

时间:2017-12-01 16:46:02

标签: javascript node.js

我有一个follwoing对象数组,它总是包含3个对象。 我想返回包含较大值的对象与其他两个相比较。

前面的对象将使其值的总和大于或等于之前的值。当前面的对象将相同的值之和返回到先前的值时,值1和值2应该完全匹配。例如,

如果sum(data [2])== sume(data [1]),则data [2]中的值1等于data [1]中的值1,data [2]中的value2等于value1 in数据[1]所以我可以返回任何一个。

我想我知道如何以原始的方式做到这一点但是最优雅的方法是什么?

在下面的例子中,我想返回数据[2]

data = [{
      Area: 'HongKong',
      value1: 163,
      value2: 175,
      DateCreated: 2017 - 11 - 28T17: 59:00.740Z },
    {
      Area: 'HongKong',
      value1: 163,
      value2: 176,
      DateCreated: 2017 - 11 - 28T17: 59:16.747Z },
    {
      Area: 'HongKong',
      value1: 165,
      value2: 176,
      DateCreated: 2017 - 11 - 28T17: 59:32.750Z }]
  })

2 个答案:

答案 0 :(得分:2)



const data = [{
      Area: 'HongKong',
      value1: 163,
      value2: 175,
      DateCreated: "2017 - 11 - 28T17: 59:00.740Z" },
    {
      Area: 'HongKong',
      value1: 163,
      value2: 176,
      DateCreated: "2017 - 11 - 28T17: 59:16.747Z" },
    {
      Area: 'HongKong',
      value1: 165,
      value2: 176,
      DateCreated: "2017 - 11 - 28T17: 59:32.750Z" 
    }
];

t0 = performance.now();
console.log(data.sort((a, b) => -(a.value1 + a.value2))[0]);
t1 = performance.now();
console.log("sort took " + (t1 - t0) + " milliseconds.");

// This the more appropriate way (faster)
t0 = performance.now();
console.log( data.reduce((a,b)=> (a.value1+a.value2) > (b.value1+b.value2) ? a:b ))
t1 = performance.now();
console.log("reduce took " + (t1 - t0) + " milliseconds.");




答案 1 :(得分:0)

按(value1 + value2)排序并获取第一个对象。

然而,我不清楚的是你的No previous object will have sume of values(value1,value2) larger or equal than prceeding one。如果是这种情况,data[2]将始终是答案吗?什么比这更优雅?



const data = [{
      Area: 'HongKong',
      value1: 163,
      value2: 175,
      DateCreated: "2017 - 11 - 28T17: 59:00.740Z" },
    {
      Area: 'HongKong',
      value1: 163,
      value2: 176,
      DateCreated: "2017 - 11 - 28T17: 59:16.747Z" },
    {
      Area: 'HongKong',
      value1: 165,
      value2: 176,
      DateCreated: "2017 - 11 - 28T17: 59:32.750Z" 
    }
];

console.log(data.sort((a, b) => (b.value1 + b.value2) - (a.value1 + a.value2))[0])

console.log(data.sort((a, b) => (a.value1 + a.value2) - (b.value1 + b.value2))[data.length-1])

console.log(data.sort((a, b) => (a.value1 + a.value2))[0])