« Back to the index
Array.prototype.* examples
The Array object has been enhanced with 2 extra extremely usefull methods:
indexOf: will search for the index of the specified value into the array.
remove: will remove the specified element by value.
The indexOf and remove methods will accept to work on an array of objects too, with a specified field of the objects as the second parameter.
Array.indexOf(value, field);
Array.remove(value, field);
The parameter 'field' is optional.
indexOf will return the index of the value (integer >= 0), or false.
remove will always return the Array itself so you can chain functions.
Let's build a simple array:
var simplearray = ['abc', 'def', 1,2,3,4,5,6,7,8,9,10];
function test1()
{
var text = 'Index of def: ' + simplearray.indexOf('def') + '\n';
text += 'Index of 5: ' + simplearray.indexOf(5) + '\n';
text += 'Removing the elements: 3 and abc\n';
simplearray.remove(3).remove('abc');
text += 'Index of def: ' + simplearray.indexOf('def') + '\n';
text += 'Index of 5: ' + simplearray.indexOf(5) + '\n';
WA.get('#test1').text(text);
};
Show the result
Now let's try with an array of objects:
var complexarray = [
{"id":'prod1',"name":'Video of the Space',"price":132.30},
{"id":'prod2',"name":'Book of the Sea',"price":99.90},
{"id":'prod3',"name":'Music of the Silence',"price":5.99}
];
function test2()
{
var text = 'Index of price 99.90: ' + complexarray.indexOf(99.90, 'price') + '\n';
text += 'Index of id prod3: ' + complexarray.indexOf('prod3', 'id') + '\n';
text += 'Removing the element: prod1\n';
complexarray.remove('prod1', 'id');
text = 'Index of price 99.90: ' + complexarray.indexOf(99.90, 'price') + '\n';
text += 'Index of id prod3: ' + complexarray.indexOf('prod3', 'id') + '\n';
text += 'Removing the element: prod2\n';
complexarray.remove('prod2', 'id');
text += 'Index of price 99.90: ' + complexarray.indexOf(99.90, 'price') + '\n';
text += 'Index of id prod3: ' + complexarray.indexOf('prod3', 'id') + '\n';
WA.get('#test2').text(text);
};
Show the result
« Back to the index