简体   繁体   English

如何通过数字值对javascript中的对象进行排序

[英]How to sort an an object in javascript by number value

I am trying to sort an object so that the property with the most votes comes first. 我正在尝试对对象进行排序,以使投票数最多的属性排在第一位。 Here's my data structure 这是我的数据结构 在此处输入图片说明

I have found some articles on how to do this and I have created a new array and am pushing the votes value into it as well as the player object. 我找到了一些有关如何执行此操作的文章,并创建了一个新数组,并将votes值和player对象推入其中。 The problem I am having is then sorting the options by the number, and removing the votes count from the array. 然后,我遇到的问题是按数字对选项进行排序,然后从数组中删除票数。 Here's my code 这是我的代码

    var sortedOptions = [];
    for (let option of options) {
        sortedOptions.push(option, option.votes);
    }

    sortedOptions.sort(function(a, b) {

    })

I have been following this but I don't understand how the sort function is working and how to do it for my purposes. 我一直在关注这个 ,但我不明白的排序功能是如何工作的,以及如何做到这一点,我的目的。

Thanks for your help :) 谢谢你的帮助 :)

EDIT: I tried doing the following code, however this was returning an object with 8 options and the object isn't sorted 编辑:我尝试执行以下代码,但是,这将返回带有8个选项的对象,并且该对象未排序

    sortedOptions.sort(function(a, b) {
        return a.votes - b.votes;
    })

Resulted in 导致 在此处输入图片说明

You can use Array.prototype.sort() 您可以使用Array.prototype.sort()

The sort function takes a function as an argument, which compares two elements of the array to determine which one should be sorted where. sort函数将一个函数作为参数,该函数将比较数组中的两个元素以确定应该在哪里对哪个元素进行排序。

For your case where you want to sort based on votes you write it like so: 对于要基于投票进行排序的情况,您可以这样编写:

options.sort(function(a, b) {
    // use b - a to sort descending, a - b to sort ascending
    return b.votes - a.votes;
})

The for-loop you are using is strange: it produces an array which is mixed of objects and numbers, that's why the sort function doesn't work on it. 您使用的for循环很奇怪:它产生一个由对象和数字组成的数组,这就是为什么sort函数不能在其上起作用的原因。 Either sort on options directly, or if you need a copy use let sortedOptions = JSON.parse(JSON.stringify(options)); 直接对options排序,或者如果需要复制,请使用let sortedOptions = JSON.parse(JSON.stringify(options));

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

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