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
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
5 Comments
KyelJmD
will it automatically rearrange the index?
Lin Qiu
var array = ['1', '2', '3']; array.splice(2, 1); // take index 2 and remove 1 and now the array is ['1', '3']
KyelJmD
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?
Lin Qiu
L0L thanks for compiling my code, i meant to type index[1] which is '2'
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
}