【问题标题】:sort array of objects to eliminate duplicate entries对对象数组进行排序以消除重复条目
【发布时间】:2013-01-11 19:55:10
【问题描述】:

我有这个对象数组

var ArrTdsObjects = [];

function TdMaster(id, HeaderTxt, CurrentIndex, SortOrder, Width, Color, BgColor) {
    this.id = id;
    this.HeaderTxt = HeaderTxt;
    this.CurrentIndex = CurrentIndex;
    this.SortOrder = SortOrder;
    this.Width = Width;
    this.Color = Color;
    this.BgColor = BgColor;
}
        ArrTdsObjects.push(new TdMaster(
                        CurTdID,
                        CurTdInnerTxt,
                        CurTdCellindex,
                        CurTdSortOrder,
                        CurTdWidth,
                        "color", "bgColor"
                                        )
                            );

在数组中添加了一些对象条目之后

我想根据curTdID 消除存储在ArrTdsObjects 中的重复对象

含义:数组中第一个具有相同Id的单元格将被省略,如果更高的单元格编号具有id

如果它们存在于较高的单元格编号中,我如何消除较低索引编号的数组项 意味着数组中最后添加的项目将被保存?

【问题讨论】:

    标签: javascript asp.net arrays javascript-objects arrayobject


    【解决方案1】:

    从 0 到 array.length 遍历数组并将对象添加到“散列”(阅读:javascript 多态对象)。观察:

    var objects = [...];
    var ids = {};
    for (var i = 0; i < objects.length; ++i) { ids[objects[i].id] = objects[i]; }
    // Now empty the list and push the non-duplicated objects back into it
    objects = [];
    // Check hasOwnProperty in case prototypes have been changed
    for (var id in ids) { if (ids.hasOwnProperty(id)) { objects.push(ids[id]); } }
    

    ids 每个id 只能包含一个对象,因此只有最后一个带有id 的对象将保留在ids 中。因此,您可以保证在此操作之后您的数组中只有 id 的实例。

    可能有更好的方法来清理你的数组,但是几乎可以肯定有更好的方法来做你想做的任何事情,而不必首先清理数组。

    【讨论】:

    • 例如,不要使用对象数组,而是使用“哈希”,从而保证每个 ID 永远只有一个对象。
    猜你喜欢
    • 1970-01-01
    • 2014-08-04
    • 2023-03-26
    • 2017-04-27
    • 2020-12-11
    • 1970-01-01
    • 2016-11-25
    • 2020-10-11
    • 2015-02-25
    相关资源
    最近更新 更多