简体   繁体   English

react.js按多个值排序对象

[英]react.js sort object by multiple values

I have an object which has multiple values. 我有一个具有多个值的对象。

{Object
  { value1: 1204
    value2: 5
    value3: blah
  },
  { value1: 1204
    value2: 3
    value3: blah
  },
  { value1: 942
    value2: 1
    value3: blah
  }, 
  etc
}

What I need to do is sort the object before I render it by value1 and value2 . 我需要做的是在通过value1value2呈现对象之前对对象进行排序。 I haven't found any good solutions in my online searches. 我的在线搜索没有找到任何好的解决方案。

What I have below obviously doesn't work. 我下面的内容显然不起作用。 It first sorts by value1, then resorts by value2. 它首先按value1排序,然后按value2进行排序。 I have tried a function within the sort similar to what is linked, and a few other tries. 我已经尝试了类似于链接的排序中的一个函数 ,以及其他一些尝试。 But I haven't been successful. 但我没有成功。

sortObject = (results) => {
  results.sort((a, b) => a.value1 - b.value1);
  results.sort((a, b) => a.value2 - b.value2);
  console.log(results);
  return results;
 };

What is an efficent way to sort my object? 什么是对我的对象进行排序的有效方法?

results.sort((a, b) => a.value1 - b.value1 || a.value2 - b.value2);

If the subtraction of value1 is 0 (falsy so equal), it will then perform the secondary sort based on value2. 如果value1的减法为0(假数如此相等),则它将基于value2执行二级排序。 You cannot have them in separate sorts as it does not remember previous sorts. 你不能把它们放在不同的排序中,因为它不记得以前的排序。

If you want the sort of value2 to have higher precidence, perform it first. 如果您希望value2具有更高的预测性,请先执行它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM