0

We know javascript array.push appends elements to the array. Is there an option to replace the elements in the array? The below function gets called twice and I have no control over event.mediaCollection.mediaIds. So mediaDTOs array gets populated with same number of mediaIds twice. I wish to prevent that from happening.I'm looking to add new mediaIds everytime this function is called instead of pushing mediaIds to the same array.

function calledTwice(){
    var mediaIds = event.mediaCollection.mediaIds; 
    var mediaDTOs = [];
    for(var i = 0; i < mediaIds.length; i++) {
            mediaDTOs.push({id:mediaIds[i]});
    }
}

Edit: Can't afford to create a temporary object to achieve this. Got to get the ids in the mediaDTOs array to be unique.

2
  • Does mediaDTO's NEED to be an array? Commented Jan 20, 2012 at 0:53
  • Sorry for not being really clear, but xpapad has almost got what I was looking for. mediaDTOs needs to be an array, I'm not really understanding what difference an object would make? Commented Jan 20, 2012 at 1:28

2 Answers 2

2

change

mediaDTOs.push({id:mediaIds[i]});

to

mediaDTOs[i] = {id:mediaIds[i]};

but since mediaDTOs is local, I am not sure what the problem is...

Sign up to request clarification or add additional context in comments.

Comments

0

Use an object instead:

var mediaDTOs = { };
for(var i = 0; i < mediaIds.length; i++) {
   mediaDTOs[ mediaIds[i] ] = true;
}

Then you can get the unique ids with something like:

var ids = [];
for(var id in obj){
    ids.push(id);
}

Make sure you really want to make mediaDTOs local though...

1 Comment

Seems like an interesting answer. I did not understand the "obj" part though. Should I use mediaDTO instead of the obj in the second for loop?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.