473,903 Members | 4,235 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Return inex position of value in multi dim array

If I'm searching for an occurance of a value in a multi-dimensional
array how can I get it's index returned as an array, if found? For
example, if:

foo = new Array();
foo = [1, 2, 3, [4, '4a'], 5, [6, 7, 8], 9, 10];

Array.prototype .findValue = function(val) {
// blah
}

var foundInd = foo.findValue(8 );

Then searching for 8 returns [5, 2] and searching for 'fred' returns,
say, -1. It's seemed simple enough with a one dimensional array but I'm
stuck when the array is multi dimensional.
Andrew Poulos
Jul 23 '05 #1
5 2947
Andrew Poulos wrote:
If I'm searching for an occurance of a value in a multi-dimensional
array how can I get it's index returned as an array, if found? For
example, if:

foo = new Array();
foo = [1, 2, 3, [4, '4a'], 5, [6, 7, 8], 9, 10];
The first line isn't necessary. The array literal will create an array
object.
Array.prototype .findValue = function(val) {
// blah
}

var foundInd = foo.findValue(8 );

Then searching for 8 returns [5, 2] and searching for 'fred' returns,
say, -1.


/* An array can either be an object or a function (varies by host),
* but any array should have the Array object as its constructor.
*/
function isArray(o) {
return ((o && ('object' == typeof o)) || ('function' == typeof o))
&& (Array == o.constructor);
}

/* The findValue method returns the first matching value
* using a depth-first search algorithm. If a match is
* found, the return value will be an array containing
* as many elements as necessary to subscript the match.
* If no match was found, -1 is returned.
*
* For example,
*
* [1, [2, 3], 3]
*
* searching for 3 will return [1, 1] not [2]. Searching
* for 4 will return -1.
*/
Array.prototype .findValue = function(v) {var i, j, n;
for(i = 0, n = this.length; i < n; ++i) {
/* If the current element is an array... */
if(isArray(this[i])) {
/* ...search it for matching values. */
j = this[i].findValue(v);
/* If the search was a success... */
if(-1 != j) {
/* ...create an array containing the index of
* the current element and append the result
* of searching the nested array.
*/
return [i].concat(j);
}
/* If the current element matches the search value,
* return an array containing the index of that
* element.
*/
} else if(this[i] == v) {return [i];}
}
/* If no matches have been found, return -1. */
return -1;
};

Instead of returning -1, you could also return an empty array. To do
that, modify the most-nested if statement to:

if(j.length) {

and the final return statement to:

return [];

You might also want to change the "else if" condition to use strict
equality. This would prevent '3' (string) from matching 3 (number).

[snip]

Hope that helps,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #2
JRS: In article <422627a4$0$197 99$5a62ac22@per-qv1-newsreader-
01.iinet.net.au >, dated Thu, 3 Mar 2005 07:53:03, seen in
news:comp.lang. javascript, Andrew Poulos <ap*****@hotmai l.com> posted :
If I'm searching for an occurance of a value in a multi-dimensional
array how can I get it's index returned as an array, if found? For
example, if:

foo = new Array();
foo = [1, 2, 3, [4, '4a'], 5, [6, 7, 8], 9, 10];

Array.prototyp e.findValue = function(val) {
// blah
}

var foundInd = foo.findValue(8 );

Then searching for 8 returns [5, 2] and searching for 'fred' returns,
say, -1. It's seemed simple enough with a one dimensional array but I'm
stuck when the array is multi dimensional.


Recurse.

Scan an array; if the value is found stack the index and return; if an
array is found, stack the index and scan. If nothing is found, you
should get an empty stack. The stack can be an array.

Presumably you only want the first entry.
function Scan(F, B, V) { var j
for (j=0 ; j<F.length ; j++) {
if (F[j] == V) { B[B.length]=j ; return true }
if (typeof F[j] == 'object') {
B[B.length]=j /* push */
if (Scan(F[j], B, V)) return true
B.length-- /* pop */ }
}
}

foo = [1, 2, 3, [4, '4a'], 5, [6, 7, 8], 9, 10];
bar = []
val = 8
Scan(foo, bar, val)

Answer = bar // an array value [5,2]
It may need making safer; that assumes that an object entry can be
treated as an array. Under-tested.

Actually, this also serves; but it pushes and pops more often than
needed :-

function Scan(F, B, V) { var j
for (j=0 ; j<F.length ; j++) {
B[B.length]=j
if (F[j] == V) return true
if (typeof F[j] == 'object' && Scan(F[j], B, V)) return true
B.length-- }
}

Then there is :-

function Scan(F, B, V) { var j
for (j in F) {
B[B.length]=j
if (F[j] == V) return true
if (typeof F[j] == 'object' && Scan(F[j], B, V)) return true
B.length-- }
}

foo = [1, new Date(), 3, {k:[1,8]}, [4, '4a'], 5, [6,, 7, 8], 9, 10];

giving [3,k,1]

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #3
rh
Michael Winter wrote:

<..>
/* An array can either be an object or a function (varies by host), * but any array should have the Array object as its constructor.
*/
Not that I doubt your note, but that seems to be in contravention of
ECMA 262/3 11.4.3 which says typeof == "function" implies native Object
with [[Call]] implementation.
function isArray(o) {
return ((o && ('object' == typeof o)) || ('function' == typeof o)) && (Array == o.constructor);
}


Perhaps the isArray global requirement, and the accompanying bit of
twisting, can be circumvented as in the following (minimally tested):

Array.prototype .findValue = function( val ) {
for ( var k = 0, o, ret; k < this.length; k++ ) {
if ( (o = this[k]) === val) return [k];
if (o && o.findValue === arguments.calle e
&& (ret = o.findValue( val )) ) return ret.unshift( k ), ret;
}
}

<..>

../rh

Jul 23 '05 #4
rh wrote:
Michael Winter wrote:

<..>
/* An array can either be an object or a function (varies by
* host), but any array should have the Array object as its
* constructor.
*/
Not that I doubt your note, but that seems to be in contravention
of ECMA 262/3 11.4.3 which says typeof == "function" implies native
Object with [[Call]] implementation.


I might have been thinking of something else. For example, IE seems to
think that the getElementById method is an object rather than a
function. Anyway, at worst the user has to download an extra bit of an
expression which is never executed.

[snip]
Perhaps the isArray global requirement,


The isArray function doesn't have to be global...

[snip]

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #5
rh
Michael Winter wrote:
rh wrote:
Michael Winter wrote:

<..>
/* An array can either be an object or a function (varies by
>> * host), but any array should have the Array object as its
>> * constructor.
>> */
Not that I doubt your note, but that seems to be in contravention
of ECMA 262/3 11.4.3 which says typeof == "function" implies native
Object with [[Call]] implementation.


I might have been thinking of something else.


It may be that it's evidenced in some browser/host that pre-dates the
standard. If it does exist somewhere, it would be nice to know of a
concrete example. Anything's possible, I suppose, but it would seem
particularly strange to arise as a host dependency.

<..>
Anyway, at worst the user has to download an extra bit of an
expression which is never executed.

The concern isn't there. It's the inclusion of "funny" tests, which
possibly no-one knows if, or why, they're necessary.
[snip]
Perhaps the isArray global requirement,


The isArray function doesn't have to be global...


Did you forget to put a smiley there? ;-)

../rh

Jul 23 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
3624
by: Nascimento | last post by:
Hello, How to I do to return a string as a result of a function. I wrote the following function: char prt_tralha(int num) { int i; char tralha;
7
5835
by: ashu | last post by:
look at code #include<stdio.h> int *mult(void); int main(void) { int *ptr,i; ptr=mult; for(i=0;i<6;i++) { printf("%d",*(ptr++));
11
1974
by: MLH | last post by:
The following procedures found at http://ffdba.com/downloads/Send_Mail_With_Outlook_Express.htm are meant to work together in harmony to effect eMail sends via OE. The last procedure (FN SplitB) fails on its last line which is meant to assign the value of SplitB (a variant) the value of aSplit (an array dim'd as variant). That fails due to Type Mismatch. Anyone know how to get around this? Private Type MapiRecip Reserved As Long
272
14277
by: Peter Olcott | last post by:
http://groups.google.com/group/comp.lang.c++/msg/a9092f0f6c9bf13a I think that the operator() member function does not work correctly, does anyone else know how to make a template for making two dimensional arrays from std::vectors ??? I want to use normal Array Syntax.
1
2986
by: phpCodeHead | last post by:
I know that this sounds like something overly complex - because it is. However, if I can keep the user interface the way it is, my users will be ultra happy! That is the goal... In general, this is an inventory receiving piece of an overall larger web-based ERP system. What I have is a form in which I have a dynamic number of multline textareas for inputting (possibly barcode scanning in) many serial numbers per lineitem recieved.
10
4003
by: SM | last post by:
Hello I'm trying to create a multi dimensional array in JavaScript, but after some reading i still can't figure out how to apply it to my model. Here it is: I have a list A and for each item in the list A i want to associate an undetermined number of items. The complication for me is the fact that the items to associate in list A are undetermined.
5
2034
by: shanfeng | last post by:
such as a function: f(double v, int a) could this function return both a integer and array? Thank you very much. I have confused on this for a long time~
9
2695
by: =?Utf-8?B?RGFya21hbg==?= | last post by:
Hi, I am wondering how you multi-dimension an array function? My declared function looks like this: Public Function GetCustomerList(ByVal Val1 As String, ByVal Val2 As Long, ByVal Val3 As String) As String() Previously I dimensioned a single dimension Array to the size I wanted and
152
9986
by: vippstar | last post by:
The subject might be misleading. Regardless, is this code valid: #include <stdio.h> void f(double *p, size_t size) { while(size--) printf("%f\n", *p++); } int main(void) { double array = { { 3.14 }, { 42.6 } }; f((double *)array, sizeof array / sizeof **array); return 0;
0
9999
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9847
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11283
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10501
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9685
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8049
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7206
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6093
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4727
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.