Tomek Buszewski Tomek Buszewski - 10 months ago 46
Javascript Question

Element from array being removed too early?

I'm making a simple images lazy loading mechanism. I start with an array of images to process, and when I load each one, I want to remove the said image from array.

My code is as follows:

const removeFromArray = (id) => {
const position = images.indexOf(id);

if (id.classList.contains(classes.loaded)) {
images.splice(id, 1);

const setHeight = (img, target) => {
const parentWidth = img.parentNode.offsetWidth;
const initw = target.width;
const inith = target.height;

return (parentWidth / initw) * inith;

const loadImage = (img) => {
const image = new Image();

image.src = img.getAttribute('data-lazy-img');
image.onload = function(e) {
const target = || e.srcElement; = `${setHeight(img, target)}px`;
img.src = img.getAttribute('data-lazy-img');


Problem is, sometimes the wrong image gets removed (especially when I remove the latter ones).

My whole code is here:

What can I do?

Answer Source

It seems to make no sense to call splice with an image id as parameter:

 images.splice(id, 1);

You probably meant to do this:

 images.splice(position, 1);