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)

KyelJmD
  • 4,682
  • 9
  • 54
  • 77

3 Answers3

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

Lin Qiu
  • 159
  • 4
  • will it automatically rearrange the index? – KyelJmD Sep 26 '12 at 04:28
  • var array = ['1', '2', '3']; array.splice(2, 1); // take index 2 and remove 1 and now the array is ['1', '3'] – Lin Qiu Sep 26 '12 at 04:35
  • 1
    take a look at this thread [link](http://stackoverflow.com/questions/500606/javascript-array-delete-elements) – Lin Qiu Sep 26 '12 at 04:36
  • 2
    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? – KyelJmD Sep 26 '12 at 04:38
  • L0L thanks for compiling my code, i meant to type index[1] which is '2' – Lin Qiu Sep 26 '12 at 04:43
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);
ecco88
  • 606
  • 2
  • 7
  • 16
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
   }