从javascript数组中删除具有重复属性的对象 [英] Remove objects with a duplicate property from a javascript array

查看:838
本文介绍了从javascript数组中删除具有重复属性的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含几个对象的JavaScript数组,每个对象具有以下格式:

I have a javascript array that contains several objects, each object having this format:

{'hits':21, 'date':2011-01-11, 'business_id':233}

我正在使用排序对数组对象进行排序的功能:

I am using a sorting function to sort the array objects:

    my_array.sort(function(a, b){
        return b.hits-a.hits;
    });

此排序导致具有相同business_id的相邻对象。我想删除那些具有重复的'business_id'的那些,只保留那些具有最新日期值的重复项。

This sorting results in having some adjacent objects with the same 'business_id'. I would like to remove the ones with duplicate 'business_id's to keep only the one of the duplicates having the newest date value.

如何从数组中删除对象有重复的business_id,保持最新的date值?我可以在排序函数或一些过滤器函数中执行吗?

How do I remove the objects from the array that have duplicate 'business_id', keeping the one with the newest 'date' value? Can I do it in the sort function, or with some filter function?

推荐答案

如果使用主对象,将business_id映射到对象,这将会更简单。这样,每当你将一个对象添加到主人时,你会检查它是否已被定义。然后,您可以比较日期,看看是否要更换。

If you use a master object, mapping business_id to objects, it'd be a lot simpler. This way, every time you add one of your objects to the master, you'd check to see if it was already defined. Then, you'd compare dates to see if you want to replace it.

这篇关于从javascript数组中删除具有重复属性的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆