-1

I feel like an idiot, but I just can't figure this one out. I'm creating an array of objects:

var files = [];

for (var a = 0; a < data.Attachments.length; a++) {
    files.push({
        id: data.Attachments[a].ID,
        name: data.Attachments[a].Name, 
        size: data.Attachments[a].Size, 
        extension: data.Attachments[a].Extension 
    });                 
}       

And I need to prevent duplicate entries from being added to the array. I've tried a variety of ways to access and check the existing IDs before pushing the new row (including this thread), but nothing has worked. I'm sure it's some little thing I'm just missing.

Here's what a console.log of the files array looks like after it's been populated (it's looping through multiple items and creating an array for each of them; some items don't have attachments): enter image description here

Community
  • 1
  • 1
shimmoril
  • 682
  • 1
  • 11
  • 22

1 Answers1

1

I believe you can setup a cache object to record what has already been added to the array. Each time before you wanna push a new item into the array, check if that item is already recorded in the cache object. If it is, continue to the next item; otherwise push it into the array.

Something like this:

var files = [];
var cache = {};

for (var a = 0; a < data.Attachments.length; a++) {
    if (!cache.hasOwnerProperty(data.Attachments[a].ID)) {
        files.push({
            id: data.Attachments[a].ID,
            name: data.Attachments[a].Name, 
            size: data.Attachments[a].Size, 
            extension: data.Attachments[a].Extension 
        });
        cache[data.Attachments[a].ID] = 0 // doesn't matter what value you assign
    }                 
}

Hope this helps and let me know if it works.

Yu Wu
  • 213
  • 2
  • 7