On Nov 10, 8:28 pm, "thibault.langlois" <thibault.langl...@gmail.com>
wrote:
Hello,
I am in my first day of javascript programming.
Welcome to the club! :-)
I would like to find the position of an object in an array such that
one of its attribute has a certain value. Is it possible to pass the
attribute name as a parameter ?
function elementPosition (element, array, attribute) {
var i = 0;
for (object in array) {
if (element == object.attribute)
return i;
i = i + 1;
}
return "";
}
In here you are iterating through the properties of an object to see
if the object has some given property with some given value. An
object with its properties - programmatically - is a set of key/value
pairs, other words an "associative array" or "hash". There is no
"position" in this structure as such. You can only add, remove and
check for existence particular key/value pairs. For the last task
there is no need to go through all pair. If you need to check is
SomeObject has property SomeProperty and this property equals to
SomeValue then all you have to do is (w/o regular simplification to be
more visual):
if ((typeof SomeObject[SomeProperty] != 'undefined') &&
(SomeObject[SomeProperty] == SomeValue)) {
// positive match
}
Here you have to use SomeObject[SomeProperty] syntax because with
SomeObject.SomeProperty the system will look for "SomeProperty"
property - so using SomeProperty as a literal instead of the value
stored in this variable.
If you want to do what you wrote: so you have an Array of objects and
you want to see if any object has a given property with a given value
and you want to know then the position (index) of such object in your
array:
// Let's create an array with three objects in it:
var MyArray = [
{'foo':'not a bar'},
{'foo':'still not a bar'},
{'foo':'bar'},
];
// Search function:
function elementPosition(arrayReference, propertyName, soughtValue) {
// The match may happen on the first element in the array
// (index 0) so we are using negative value
// for "no match found" like in indexOf / lastIndexOf
// methods:
var position = -1;
for (var i=0; i<arrayReference.length; i++) {
if (arrayReference[i][propertyName] == soughtValue) {
position = i;
break;
}
}
return position;
}
alert(elementPosition(MyArray, 'foo', 'bar'));
// alerts 2 - the 3rd element in the array