Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I splice a new image into an array in the same position that the image that I want to remove is in and to display this image

I have an array of images. Each image is clickable and generates a message.The images are in a random array. This all works fine. What I am failing to achieve is the following:
When the image is clicked it becomes obsolete so I want to replace the clickable image with a new, unclickable image.
I have tried using the array.splice method as follows
newArray=myImages.splice(evt.target,1,newImage)
This places the new image at position 0 in the new array and not in its original position and no new image is produced to overwrite the older image.
I would be grateful for any help.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If we guess that evt in newArray=myImages.splice(evt.target,1,newImage) is an Event object, evt.target is a DOM element, not an index. If this is in the click event you describe, it will be the clicked image.

The first argument of splice is the index at which to make changes; a number. DOM elements are not numbers.

splice also returns an array of deleted images, not an updated array. (Unlike methods like map or slice, splice modifies the array you call it on.)

You can find the previous image’s index by using indexOf and then us splice with that:

const index = myImages.indexOf(evt.target);
if (index !== -1) {
    myImages.splice(index, 1, newImage);
}

or you could use map to create a new array with the new image in place of the clicked one:

newArray = myImages.map(img => img === evt.target ? newImage : img);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading