2

I am trying to find out if there is a better way to do what I am doing here.

I built a customColumn object that has some properties like ID and Title, etc...

ie. my cusColum = new aColumn('321', 'Todds Column');

Then put all of those columns into an array - so this array holds objects and not simple values.

So I am doing this to find a particular object in my array:

var len = columnObjects.length;
    for (var i = 0; i < len; i++) {
        if (columnObjects[i].colID == id) {
            columnObjects.splice(i, 1);
            break;
        }      

The splice is just one thing I am doing with these objects... I would LOVE to be able to use the IndexOf function but dont know how I would write it or if it is even possible ...

1
  • 2
    Hooray for caching the array's length Commented Dec 13, 2010 at 17:23

2 Answers 2

2

One possible solution is to use an associative array to store your columnObjects. When populating the array you would do something like:

var columnObjects = {};

// your probably populating in a loop
columnObjects['321'] = new aColumn('321', 'Todds Column');

Then when you want to get an object by id you say:

columnObjects[id];

You could also use the associative array to use multiple keys to the same object:

var id = '321';
var owner = 'Todds Column';
var column = new aColumn(id, owner);
columnObjects[id] = column;
columnObjects[owner] = column;

There are a few other solutions I can think of, but this was the first that came to mind.

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

2 Comments

Ok, that sounds fairly awesome -- my ids though are like 'col1', 'col2' ... can I use that as the id for the array or ints only? (HA! first search for associatives gave me this explanation... 'Associative arrays give you another way to store information. Using associative arrays, you can call the array element you need using a string rather than a number, which is often easier to remember.') awesome, I will try this - this should really clean up my code!
cool glad it helped, would appreciate an upvote and if this answers your question you can mark it as answered by clicking the big check mark. And yes, you can use things like col1 col2 for your index values.
0

You could use Linq

var objectsFound = Enumerable.From(columnObjects).Where(function (x) {
                    return x.colID === id}).FirstOrDefault(null);

if (objectsFound)
  do something....

Comments

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.