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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Should this return where in the list the object occurs, or just the number of occurrences?
oops, like I missed the position part, you can still use join and index, updating the post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.