1

Supposed I have a response of

enter image description here

and I'm looping it via and push the pic.id on files array

files = []

response.data[0].pics.forEach(function(pic, i){
      let div = makeButtons(response.data[0].pics, files, imgPrevEdit);
      files.push(pic.id);
});

so after pushing the file array will become like this

enter image description here

the make button function is use to delete that certain element on the array using splice function

makeButtons: function(file, store, elem) {
    let button = document.createElement("button");
    button.classList.add('position-absolute','x', 'rounded-circle');
    button.type = "button";
    button.innerHTML= "x";

    button.addEventListener('click', () => {
        elem.removeChild(div);
        store.splice(store.indexOf(file), 1);
    });

    let div = document.createElement("div");
    div.classList.add('col', 'mt-2');
    div.appendChild(button);
    return div;
},

However when i click the button it always start at the end of files array it doesnt find the specific key and delete it

any idea how can i solve it?

Beginner
  • 1,700
  • 4
  • 22
  • 42

1 Answers1

1

it always start at the end of files array

I think it happens because store.indexOf(file) returns -1. In this case splice

will begin that many elements from the end of the array (with origin -1, meaning -n is the index of the nth last element and is therefore equivalent to the index of array.length - n)

Why store.indexOf(file) returns -1? Because you pass response.data[0].pics as file argument, but you actually push pic.id to files which you pass as store:

let div = makeButtons(response.data[0].pics, files, imgPrevEdit);
files.push(pic.id);
Kirill Simonov
  • 8,257
  • 3
  • 18
  • 42