The main task in this recipe is to find out whether an arbitrary object exists in an array. A way to remove objects from the array is also explored.
The following steps illustrate how you can perform object existence tests and object removal in an array:
1. Create a sample array as follows:
var colorsArray = new Array(); colorsArray[0] = 'Blue'; colorsArray[1] = 'Red'; colorsArray[2] = 'White';
2. Determine whether an object exists in an array by trying to find its position in the array:
var position = colorsArray.indexOf('White'); // postition is 2, the index of 'White' in the array. position = colorsArray.indexOf('Brown'); // 'Brown' does not exist in the array, // position is -1.
3. Remove one of the objects from the array:
colorsArray.remove('Blue'); position = colorsArray.indexOf('Blue'); // 'Blue' does not exist anymore, // position is -1.
Ext JS augments the native Array
class with Array.indexOf(object)
and Array.remove(object)
. While indexOf(object)
works by examining each array element until it finds one that matches the supplied argument, remove(object)
uses the native Array.splice(index, howmany, element1,....., elementX)
function to remove the supplied argument from the array.