热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

按对象数组中的值为对象分配排名-Assignrankstoobjectsbyvaluesinanarrayofobjects

Ihaveanarrayofobjectslikeso:我有一个像这样的对象数组:vardata{a:[{keyone:c,keytw

I have an array of objects like so:

我有一个像这样的对象数组:

var data = {
    a: [
        { keyone:'c', keytwo: 'anna', keythree: 21, keyfour: 15 },
        { keyone:'a', keytwo: 'anna', keythree: 22, keyfour: 15 },
        { keyone:'s', keytwo: 'anna', keythree: 10, keyfour: 15 },
        { keyone:'v', keytwo: 'anna', keythree: 7, keyfour: 15 }
    ],

    b: [
        { keyone:'f', keytwo: 'any', keythree: 45, keyfour: 100 },
        { keyone:'b', keytwo: 'any', keythree: 146, keyfour: 100 },
        { keyone:'t', keytwo: 'any', keythree: 23, keyfour: 100 },
        { keyone:'h', keytwo: 'any', keythree: 11, keyfour: 100 }
    ]
  };

I want to assign ranks to each object, based on values of keythree and keyfour, within the groups as well as within the entire data set. How would I do it?

我想根据keythree和keyfour的值,在组内以及整个数据集中为每个对象分配排名。我该怎么办?

Update: I have depicted the ranks in my code above.

更新:我在上面的代码中描述了排名。

Resultant object:

结果对象:

var data = {
    a: [
        { keyone:'c', keytwo: 'anna', keythree: 21, keyfour: 15, rankgroup: 3, rankall: 4 },

        { keyone:'a', keytwo: 'anna', keythree: 22, keyfour: 15, rankgroup: 4, rankall: 5 },

        { keyone:'s', keytwo: 'anna', keythree: 22, keyfour: 15, rankgroup: 2, rankall: 2 },

        { keyone:'v', keytwo: 'anna', keythree: 7, keyfour: 15, rankgroup: 1, rankall: 1 }
    ],

    b: [
        { keyone:'f', keytwo: 'any', keythree: 45, keyfour: 100 },

        { keyone:'b', keytwo: 'any', keythree: 146, keyfour: 100 },

        { keyone:'t', keytwo: 'any', keythree: 23, keyfour: 100 },

        { keyone:'h', keytwo: 'any', keythree: 11, keyfour: 100 }
    ]
};

I am using lodash. My idea is to first sort the array based on those keys, then loop over the original object, insert the sorted index by comparing another key. This is what I have tried:

我正在使用lodash。我的想法是首先根据这些键对数组进行排序,然后遍历原始对象,通过比较另一个键来插入排序的索引。这是我尝试过的:

var keys = Object.keys(data);
var result = {};
var numkeys;
for(var i=0; i 

How would I do it? My logic seems too complex and the set method does not update the original object by key but adds a new entry after the main object.

我该怎么办?我的逻辑看起来太复杂了,set方法不会按键更新原始对象,而是在主对象之后添加一个新条目。

Update: Notice the duplicate occurrence of 22 for the object a. This leads to an issue when assigning ranks, since indexOf will always return the index of the first occurrence, hence the second occurrence will never have an index assigned to it and hence the value will be undefined.

更新:注意对象a的重复出现22。这导致在分配排名时出现问题,因为indexOf将始终返回第一次出现的索引,因此第二次出现将永远不会为其分配索引,因此该值将是未定义的。

2 个解决方案

#1


1  

this is how I achieved it.

这就是我实现它的方式。

  1. collect all keythree into an array and sort them (to assign rankall based on index).

    将所有keythree收集到一个数组中并对它们进行排序(根据索引分配rankall)。

    var all = [];
    _.forEach(data, function (a, key) {
        _.forEach(a, function(n, k){
        all.push(n.keythree);
      });
    });
    all.sort(function(a,b){
        return a-b;
    });
    
  2. assign ranks

    分配排名

    _.forEach(data, function (a, key) {
        var sorted = _.sortBy(a, 'keythree');
        _.forEach(sorted, function(n, k) {
          var index = _.findIndex(data[key], {keyone: n.keyone});
          data[key][index]['rankgroup'] = k+1;
          data[key][index]['rankall'] = all.indexOf(n.keythree)+1;
        });
    });
    

check this fiddle

检查这个小提琴


EDIT

i'm creating another array for dupes

我正在为dupes创建另一个数组

_.forEach(a, function(n, k) {
    if (all.indexOf(n.keythree) !== -1) {
        dupes.push(n.keythree);
    }
    all.push(n.keythree);
});

and for getting the global rank for these dupe items

并获得这些欺骗项目的全球排名

    function getGlobalRank(n) {
    var val = n.keythree;
    if (sorted_dupes[val] === undefined) {
        sorted_dupes[val] = [];
        _.forEach(data, function(a, key) {
            _.forEach(_.where(a, {
                keythree: val
            }), function(b) {
                sorted_dupes[val].push(b);
            });
        });
        sorted_dupes[val] = _.sortByAll(sorted_dupes[val], ['keyfour', 'keytwo', 'keyone']);
    }
    return _.findIndex(sorted_dupes[val], {
        keyone: n.keyone,
        keytwo: n.keytwo,
        keythree: n.keythree,
        keyfour: n.keyfour
    }) + 1 + all.indexOf(val);
}

see that the items are sorted based on all the properties in the order keythree, keyfour, keytwo, keyone (you can change the order inside _.sortByAll if you want to)

看到项目是根据订单keythree,keyfour,keytwo,keyone中的所有属性进行排序的(如果你愿意,你可以改变_.sortByAll中的顺序)

the code looking uglier than i thought. will update the refactored code soon

代码看起来比我想象的更丑。将很快更新重构的代码

check the fiddle

检查小提琴

#2


1  

Just in plain Javascript:

只是简单的Javascript:

For ranking, the data must be sorted, somehow.

对于排名,必须以某种方式对数据进行排序。

This solution features an array with objects and the references to the given objects in data. Then all items are sorted and the original data gets their rankgroup and rankall property.

此解决方案具有一个包含对象的数组以及对数据中给定对象的引用。然后对所有项目进行排序,并且原始数据获得其rankgroup和rankall属性。

Edit: Now with same rank for duplicates.

编辑:现在具有相同的重复等级。

var data = { a: [{ keyone: 'g', keytwo: 'tina', keythree: 21, keyfour: 15 }, { keyone: 'c', keytwo: 'anna', keythree: 21, keyfour: 15 }, { keyone: 'a', keytwo: 'anna', keythree: 22, keyfour: 15 }, { keyone: 's', keytwo: 'anna', keythree: 10, keyfour: 15 }, { keyone: 'v', keytwo: 'anna', keythree: 7, keyfour: 15 }], b: [{ keyone: 'f', keytwo: 'any', keythree: 45, keyfour: 100 }, { keyone: 'b', keytwo: 'any', keythree: 146, keyfour: 100 }, { keyone: 't', keytwo: 'any', keythree: 23, keyfour: 100 }, { keyone: 'h', keytwo: 'any', keythree: 11, keyfour: 100 }] },
    group = {};

Object.keys(data).reduce(function (r, k) {
    return r.concat(data[k].map(function (a) {
        return { obj: k, ref: a };
    }));
}, []).sort(function (a, b) {
    return a.ref.keythree - b.ref.keythree || a.ref.keyfour - b.ref.keyfour;
}).forEach(function (a, i, aa) {
    if (i && a.ref.keythree === aa[i - 1].ref.keythree && a.ref.keyfour === aa[i - 1].ref.keyfour) {
        a.ref.rankgroup = group[a.obj];
        a.ref.rankall = group.rankall;
    } else {
        group[a.obj] = (group[a.obj] || 0) + 1;
        group.rankall = (group.rankall || 0) + 1;
        a.ref.rankgroup = group[a.obj];
        a.ref.rankall = group.rankall;
    }
});

document.write('
' + JSON.stringify(data, 0, 4) + '
');


推荐阅读
  • 本文介绍了获取关联数组键的列表的方法,即使用Object.keys()函数。同时还提到了该方法在不同浏览器的支持情况,并附上了一个代码片段供读者参考。 ... [详细]
  • 模板引擎StringTemplate的使用方法和特点
    本文介绍了模板引擎StringTemplate的使用方法和特点,包括强制Model和View的分离、Lazy-Evaluation、Recursive enable等。同时,还介绍了StringTemplate语法中的属性和普通字符的使用方法,并提供了向模板填充属性的示例代码。 ... [详细]
  • 本文介绍了在使用Laravel和sqlsrv连接到SQL Server 2016时,如何在插入查询中使用输出子句,并返回所需的值。同时讨论了使用CreatedOn字段返回最近创建的行的解决方法以及使用Eloquent模型创建后,值正确插入数据库但没有返回uniqueidentifier字段的问题。最后给出了一个示例代码。 ... [详细]
  • 如何自行分析定位SAP BSP错误
    The“BSPtag”Imentionedintheblogtitlemeansforexamplethetagchtmlb:configCelleratorbelowwhichi ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 阿,里,云,物,联网,net,core,客户端,czgl,aliiotclient, ... [详细]
  • Android JSON基础,音视频开发进阶指南目录
    Array里面的对象数据是有序的,json字符串最外层是方括号的,方括号:[]解析jsonArray代码try{json字符串最外层是 ... [详细]
  • 本文详细介绍了Spring的JdbcTemplate的使用方法,包括执行存储过程、存储函数的call()方法,执行任何SQL语句的execute()方法,单个更新和批量更新的update()和batchUpdate()方法,以及单查和列表查询的query()和queryForXXX()方法。提供了经过测试的API供使用。 ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • 本文介绍了使用哈夫曼树实现文件压缩和解压的方法。首先对数据结构课程设计中的代码进行了分析,包括使用时间调用、常量定义和统计文件中各个字符时相关的结构体。然后讨论了哈夫曼树的实现原理和算法。最后介绍了文件压缩和解压的具体步骤,包括字符统计、构建哈夫曼树、生成编码表、编码和解码过程。通过实例演示了文件压缩和解压的效果。本文的内容对于理解哈夫曼树的实现原理和应用具有一定的参考价值。 ... [详细]
  • 本文介绍了解决Facebook脸书面试题中插入区间的方法,通过模拟遍历的方式判断当前元素与要插入元素的关系,找到插入点并将新区间插入。同时对算法的时间复杂度和空间复杂度进行了分析。 ... [详细]
  • 合并列值-合并为一列问题需求:createtabletab(Aint,Bint,Cint)inserttabselect1,2,3unionallsel ... [详细]
  • 本文介绍了一个React Native新手在尝试将数据发布到服务器时遇到的问题,以及他的React Native代码和服务器端代码。他使用fetch方法将数据发送到服务器,但无法在服务器端读取/获取发布的数据。 ... [详细]
  • 本文讨论了如何在dotnet桌面(Windows)应用程序中添加图标。作者提到可以使用dotnet命令行工具与resource.rc文件一起使用来为标准.NET核心应用程序添加图标。作者还介绍了在创建控制台应用程序时如何编辑projeto1.csproj文件来添加图标。 ... [详细]
author-avatar
rita
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有