0

If I have an array similar to this:

var myArray:Array = new Array("a","b","c","d","e","f","g","b");

How can I search it to determine the number of times of value appears in it and in what positions? I found the code below which is close but it will only return the first occurrence.

function findIndexInArray(value:Object, arr:Array):Number {
    for (var i:uint=0; i < arr.length; i++) {
        if (arr[i]==value) {
            return i;
        }
    }
    return NaN;
}

var myArray:Array = new Array("a","b","c","d","e","f","g","b");
trace(findIndexInArray("b", myArray));

// OUTPUT
// 1
1
0

You might consider returning an Array of indicies where the search term exists. For example:

var list:Array = ['a', 'b', 'b', 'c', 'd', 'e', 'f'];

function find(obj:Object, list:Array):Array
{
    var result:Array = [];
    for(var i:int = 0; i < list.length; i++)
    {
        if(list[i] = obj)
        {
            result.push(i);
        }
    }
    return result;
 }

 var search:Array = find('b', list);
 trace('b is found: ' + search.length + ' times at indices: ' + search); 
 // -- 'b is found: 2 times at indices [1, 2]

This way you can see how many times the search term occurs by checking the length of the returned array.

| improve this answer | |
0
0

you could use join and regex to do the count

something like this:

// convert to one long string
var str:String = myArray.join("");

// regex find the letter and count result
var count:int = str.match(new RegExp(letter,"a")).length; 

haven't tested it, so the code might need a tweak, but this should be faster than looping through the array.


update

// convert to one long string
var str:String = myArray.join("");

var pos:Array = new Array();       
var n:int = -1;     

// loop through array and find all indexes
while ((n = str.indexOf(searchFor, n+1)) != -1) pos.push(n); 

just a warning though, this will break if any string in the array has more than one character

| improve this answer | |
  • Should this return where in the list the object occurs, or just the number of occurrences? – JeremyFromEarth Mar 19 '13 at 18:05
  • oops, like I missed the position part, you can still use join and index, updating the post – Daniel Mar 20 '13 at 15:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.