質問

i have this array of objects

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"
                                        )
                            );

after a few object entries have been added to the array

i want to eliminate duplicates of objects that are stored in the ArrTdsObjects based on curTdID

meaning: the first cell in array with same Id will be left out if the higher cell number has that id

how can i eliminate lower index number array items if they exist in higher cell number meaning the last added items in array will be the ones that will be saved ?

役に立ちましたか?

解決

Iterate through the array from 0 to array.length and add the objects to a "hash" (read: javascript polymorphic object). Observe:

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 can only contain one object per id, so only the last object with id will remain in ids. Thus you are guaranteed to only have on instance of id in your array after this operation.

There may be better ways to clean up your array, but then there are almost certainly better ways to do whatever you're trying to do without having to clean up the array in the first place.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top