array of objects, lookup

T

thibault.langlois

Hello,
I am in my first day of javascript programming.

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 "";
}

If not, is it correct to pass a function name:

function elementPosition (element, array, test) {
var i = 0;
for (object in array) {
if (test (element, object))
return i;
i = i + 1;
}
return "";
}

function test1 (value, object) {
return (object.someSlot == value);
}

Are there better ways to do this in javascript ?

Thanks

Thibault Langlois
 
T

Thomas 'PointedEars' Lahn

thibault.langlois said:
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 ?

Yes, it is.
function elementPosition (element, array, attribute) {
var i = 0;
for (object in array) {
if (element == object.attribute)

This won't work because the test will be against the `attribute' property
value, not the value of the property with the name that `attribute' stores.

Also note that `==' is a type-converting comparison. Use `===' instead.
return i;
i = i + 1;
}
return "";

You want the numeric index, so it does not make sense to return the empty
string. Instead, you should return a number that can't be an index value.

And if you want the index, there really is no point in using for..in:

function elementPosition(element, array, attribute)
{
for (var i = array.length; i--;)
{
if (element === array[attribute])
return i;
}

return -1;
}
If not, is it correct to pass a function name: [...]

Yes, it is.


PointedEars
 
V

VK

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[propertyName] == soughtValue) {
position = i;
break;
}
}
return position;
}

alert(elementPosition(MyArray, 'foo', 'bar'));
// alerts 2 - the 3rd element in the array
 
T

thibault.langlois

Yes, it is.


This won't work because the test will be against the `attribute' property
value, not the value of the property with the name that `attribute' stores.

OK. thanks.
Also note that `==' is a type-converting comparison. Use `===' instead.
return i;
i = i + 1;
}
return "";

You want the numeric index, so it does not make sense to return the empty
string. Instead, you should return a number that can't be an index value.

indeed.

And if you want the index, there really is no point in using for..in:

function elementPosition(element, array, attribute)
{
for (var i = array.length; i--;)
{
if (element === array[attribute])


in this case array is a bi-dimensional array and attribute must be an
integer ?
return i;
}

return -1;
}
If not, is it correct to pass a function name: [...]

Yes, it is.

PointedEars
--
Anyone who slaps a 'this page is best viewed with Browser X' label on
a Web page appears to be yearning for the bad old days, before the Web,
when you had very little chance of reading a document written on another
computer, another word processor, or another network. -- Tim Berners-Lee
 
T

Thomas 'PointedEars' Lahn

thibault.langlois said:
And if you want the index, there really is no point in using for..in:

function elementPosition(element, array, attribute)
{
for (var i = array.length; i--;)
{
if (element === array[attribute])


in this case array is a bi-dimensional array and attribute must be an
integer ?


Not at all. From whoever/whatever you got the notion that the bracket
property accessor syntax required an Array object (probably a [bad] book),
forget about them/it regarding programming in ECMAScript implementations.

The value of `i' here is the name of a property of the Array object referred
to by `array'. It only happens that the properties of Array objects that
refer to elements of the encapsulated array data structure have an unsigned
32-bit Integer representation (see the ECMAScript Language Specification Ed.
3 Final, section 15.4.)

So `array' refers to the value of an array element. If that value is a
reference to an object (or a primitive value that can be converted into an
object), that object has properties as well. Therefore, array[attribute]
refers to the value of the property of the object array refers to that
has the name that is stored in `attribute'. And that name may have, but
does not have to have, a numeric representation.


Please trim your quotes as explained and recommended in the FAQ (Notes).
http://www.jibbering.com/faq/faq_notes/clj_posts.html


PointedEars
 
T

Thomas 'PointedEars' Lahn

thibault.langlois said:
And if you want the index, there really is no point in using for..in:

function elementPosition(element, array, attribute)
{
for (var i = array.length; i--;)
{
if (element === array[attribute])


in this case array is a bi-dimensional array and attribute must be an
integer ?


Not at all. From whoever/whatever you got the notion that the bracket
property accessor syntax required an Array object (probably a [bad] book),
forget about them/it regarding programming in ECMAScript implementations.

The value of `i' here is the name of a property of the Array object referred
to by `array'. It only happens that the properties of Array objects that
refer to elements of the encapsulated array data structure have an unsigned
32-bit Integer representation (see the ECMAScript Language Specification Ed.
3 Final, section 15.4.)

So `array' refers to the value of an array element. If that value is a
reference to an object (or a primitive value that can be converted into an
object), that object has properties as well. Therefore, array[attribute]
refers to the value of the property of the object array refers to that
has the name that is stored in `attribute'. And that name may have, but
does not have to have, a numeric representation.


Please trim your quotes as explained and recommended in the FAQ (Notes).
http://www.jibbering.com/faq/faq_notes/clj_posts.html


PointedEars
 
T

thibault.langlois

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[propertyName] == soughtValue) {
position = i;
break;
}
}
return position;

}

alert(elementPosition(MyArray, 'foo', 'bar'));
// alerts 2 - the 3rd element in the array


OK.
To be a little more precise I have objects made with this function :

function MyPhoto(elementId, selected, callback) {
this.elementId = elementId;
this.selected = selected;
this.callback = callback;
}

I want keep an array of objects that have the property selected =
"yes". Initially:

var selectedPhotos = new Array ();

When the user clicks twice on a photo it becomes unselected so I want
to know the position (in the array) of the photo that have the
attribute selected = "no" in order to remove it.

In order to make things more generic and following the advices that
were given:

function positionIf (array, test) {
for (var i = 0; i < array.length; i++;) {
if (test(value, object))
return i;
}
return -1;
}

Then, in my case I would use the test function:

function notSelected (object) {
return (object.selected === "no");
}

(ok, I usually program in Common Lisp :) )

As a novice, I may ask a stupid question ...
Lokking at your example:
// Let's create an array with three objects in it:
var MyArray = [
{'foo':'not a bar'},
{'foo':'still not a bar'},
{'foo':'bar'},
];

is it roughly equivalent to do:
function thing(foo) {
this.foo = foo
}

MyArray = new Array();
MyArray[0] = new thing("not a bar");
MyArray[1] = new thing("still not a bar");
MyArray[2] = new thing("bar");

or is it something different ? a bi-dmensional array ?

Until now the only doc I used is the javascript tutorial at:
http://www.w3schools.com/js/
do you have any recomendation for a good on-line documentation ?

Thanks,

Thibault
 
T

thibault.langlois

thibault.langlois said:
[...] Thomas 'PointedEars' Lahn [...] wrote: [...]
in this case array is a bi-dimensional array and attribute must be an
integer ?

Not at all. From whoever/whatever you got the notion that the bracket
property accessor syntax required an Array object (probably a [bad] book),
forget about them/it regarding programming in ECMAScript implementations.

Right. I have no book yet :-(
The value of `i' here is the name of a property of the Array object referred
to by `array'. It only happens that the properties of Array objects that [...]
So `array' refers to the value of an array element. If that value is a
reference to an object (or a primitive value that can be converted into an
object), that object has properties as well. Therefore, array[attribute]
refers to the value of the property of the object array refers to that
has the name that is stored in `attribute'. And that name may have, but
does not have to have, a numeric representation.


I see. I have send another post before reading yours. You answered
here. thanks.
Please trim your quotes as explained and recommended in the FAQ

I'll do my best.

(Notes).http://www.jibbering.com/faq/faq_notes/clj_posts.html
PointedEars
--

Thibault
 
V

VK

I want keep an array of objects that have the property selected =
"yes". Initially:

var selectedPhotos = new Array ();

When the user clicks twice on a photo it becomes unselected so I want
to know the position (in the array) of the photo that have the
attribute selected = "no" in order to remove it.

For this situation another doable option could also be a hash of
objects: that will save you from iterations on each removal.
JavaScript doesn't support hash with object references used as keys,
the keys have to be strings - but you might map by image name or id:

var ImageHash = {
'img01' : imgObject1,
'img02' : imgObject2,
'img03' : imgObject3,
}

function onImageDblClick(img) {
delete ImageHash[img.id];
}

That may not be an option if you need to keep the exact order in which
images were added to the selection, then stay with Array.
In order to make things more generic and following the advices that
were given:

function positionIf (array, test) {
for (var i = 0; i < array.length; i++;) {
if (test(value, object))
return i;
}
return -1;

}

Then, in my case I would use the test function:

function notSelected (object) {
return (object.selected === "no");

}

(ok, I usually program in Common Lisp :) )

So you will be comfortable with anonymous functions :)
As a novice, I may ask a stupid question ...
Loking at your example:
// Let's create an array with three objects in it:
var MyArray = [
{'foo':'not a bar'},
{'foo':'still not a bar'},
{'foo':'bar'},
];

is it roughly equivalent to do:
function thing(foo) {
this.foo = foo

}

MyArray = new Array();
MyArray[0] = new thing("not a bar");
MyArray[1] = new thing("still not a bar");
MyArray[2] = new thing("bar");

or is it something different ? a bi-dmensional array ?

No, it is a single-dimensional array created over squared brackets
notation instead of explicit constructor call.

var MyArray = [
{'foo':'not a bar'},
{'foo':'still not a bar'},
{'foo':'bar'},
];

is equal to:

var MyArray = new Array(
{'foo':'not a bar'},
{'foo':'still not a bar'},
{'foo':'bar'} );

We are filling the array with generic Object instances using {}
brackets notation instead of explicit Object constructor call. In your
sample:
MyArray = new Array();
MyArray[0] = new thing("not a bar");
MyArray[1] = new thing("still not a bar");
MyArray[2] = new thing("bar");

you are filling the array with instances of "thing" class that extends
generic Object class. So in my sample
(MyArray[0] instanceof thing) == false
and in your sample
(MyArray[0] instanceof thing) == true

Because in JavaScript each class extends the generic Object class,
in either case
(MyArray[0] instanceof Object) == true

If you ever worked with Java, this fact should not surprise you. I am
not sure about Common Lisp, my experience is limited here by AutoCAD
Lisp w/o OOP usage.
Until now the only doc I used is the javascript tutorial at:http://www.w3schools.com/js/
do you have any recomendation for a good on-line documentation ?

May sound heretical :) but Microsoft docs are good for start-up
reading. You also can download the entire doc as a Windows help file:
http://www.microsoft.com/downloads/details.aspx?FamilyId=01592C48-207D-4BE1-8A76-1C4099D7BBB9
 
T

thibault.langlois

[...]
If you ever worked with Java, this fact should not surprise you. I am

Yes. I have experience with other programming languages and prototype-
based OOP so your explanations are very clear for me.
Thanks a lot. It is now time for me to read.
not sure about Common Lisp, my experience is limited here by AutoCAD
Lisp w/o OOP usage.


May sound heretical :) but Microsoft docs are good for start-up
reading. You also can download the entire doc as a Windows help file:http://www.microsoft.com/downloads/details.aspx?FamilyId=01592C48-207...

I will check that. thanks.

Thibault.
 
T

Thomas 'PointedEars' Lahn

VK said:
On Nov 11, 5:29 am, "thibault.langlois" <[email protected]>
wrote:
[...]
We are filling the array with generic Object instances using {}

The term "instance" relates to class-based OOP and does not apply here.
[...]
MyArray = new Array();
MyArray[0] = new thing("not a bar");
MyArray[1] = new thing("still not a bar");
MyArray[2] = new thing("bar");

you are filling the array with instances of "thing" class that extends
generic Object class. So in my sample
(MyArray[0] instanceof thing) == false
and in your sample
(MyArray[0] instanceof thing) == true

Because in JavaScript each class extends the generic Object class,

Nonsense. In client-side JavaScript (1.8) and JScript (5.6) so far there
are no classes. Implementations of ECMAScript Ed. 3 are object-oriented
programming languages that use prototype-based inheritance. There are no
classes and no instances, there are but objects, even though the
`instanceof' operator suggests otherwise.

The truth is that every native object either has Object.prototype as its
prototype object or an object that inherits from Object.prototype through
the prototype chain.

http://developer.mozilla.org/en/doc...ide:Class-Based_vs._Prototype-Based_Languages
[...]
Until now the only doc I used is the javascript tutorial at:http://www.w3schools.com/js/
do you have any recomendation for a good on-line documentation ?

May sound heretical :) but Microsoft docs are good for start-up
reading. You also can download the entire doc as a Windows help file:
http://www.microsoft.com/downloads/details.aspx?FamilyId=01592C48-207D-4BE1-8A76-1C4099D7BBB9

The documentation of Microsoft JScript is good for learning Microsoft
JScript, Microsoft's ECMAScript implementation that can be used client-side
in applications using MSHTML (such as MS Internet Explorer), and server-side
within ASP and ASP.NET.

It is not good for learning JavaScript, Netscape/Mozilla.org's ECMAScript
implementation, and it is certainly not good for learning about ECMAScript
in general.

http://PointedEars.de/scripts/es-matrix

Links to proper reference material are contained in the newsgroup's FAQ:

http://jibbering.com/faq/

Subscribers are strongly advised not to listen to VK's fairytales; details
can be found in the newsgroup's archives:

http://groups.google.com/groups?as_ugroup=comp.lang.javascript&as_uauthors=VK&scoring=d&filter=0


PointedEars
 
V

VK

:))
After the recent lost of the English soccer team to Russians, a new
British joke at the next morning was: "It is already 9am and Steve
Mclaren is still the coach. What a hey delay?".
By using this template: "VK is already two days as back to clj and
Thomas is still posting in here. What is he still doing here?" You had
your fun during my absence since this May, but now the fun is over,
thank you for your time.
:))


:-|
I will not argue with you as have nothing interesting to say - to me
at least.
:-|
 
T

Thomas 'PointedEars' Lahn

thibault.langlois said:
thibault.langlois said:
[...] Thomas 'PointedEars' Lahn [...] wrote: [...]
in this case array is a bi-dimensional array and attribute must be an
integer ?
Not at all. From whoever/whatever you got the notion that the bracket
property accessor syntax required an Array object (probably a [bad] book),
forget about them/it regarding programming in ECMAScript implementations.

Right. I have no book yet :-(

Don't bother. I can recommend none, and there are several I can recommend
against. You are best off with this group, it's FAQ, FAQ Notes, and the
reference material pointed to therein.


PointedEars
 
T

Thomas 'PointedEars' Lahn

thibault.langlois said:
thibault.langlois said:
[...] Thomas 'PointedEars' Lahn [...] wrote: [...]
in this case array is a bi-dimensional array and attribute must be an
integer ?
Not at all. From whoever/whatever you got the notion that the bracket
property accessor syntax required an Array object (probably a [bad] book),
forget about them/it regarding programming in ECMAScript implementations.

Right. I have no book yet :-(

Don't bother. I can recommend none, and there are several I can recommend
against. You are best off with this group, its FAQ, FAQ Notes, and the
reference material pointed to therein.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,277
Latest member
VytoKetoReview

Latest Threads

Top