3

I have this collection of images resources where that is stored in array, the user will select an image and then the selected image will be removed from the list(also from the array) and after that The array would be rearrange. How could I perform such task? (as much as possible I do not want to use an open source library)

3 Answers 3

5

Sounds like you need to look up splice() method. It allows you to add and remove one to many items within an array at any index.

here's reference for it. https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice

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

5 Comments

will it automatically rearrange the index?
var array = ['1', '2', '3']; array.splice(2, 1); // take index 2 and remove 1 and now the array is ['1', '3']
take a look at this thread link
take index 2 ? isn't index 2 value is 3? how come the result come the available elements is 1 and 3? isn't supposed to be 1 and 2? since index[2] == 3?
L0L thanks for compiling my code, i meant to type index[1] which is '2'
4

your question lacks a code example but you can use Array.splice(index,number) whereas index is zero based and number is how many items to remove.

images.splice(selectedIndex,1);

Comments

0

Simply, you can create a temporary array where you store the initial array elements you need and reassign the value of your initial array to the temporary array.

   function clean_array(my_array){
       var no_need_value = 'value you want to remove'
       var tmpArray = new Array()
       for (var i = 0; i < my_array.length; i++)
           if (my_array[i] != no_need_value)
               tmpArray.push(my_array[i])
       my_array = tmpeArray
   }

Comments

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.