2

I have an array of data which stores an object with functions and other such info. I push these objects to the function for my draw function to execute.

But i do not know of a way to find a specific object in an array to remove it and thus stop drawing it.

For example i have an array structure like this:

var data  = {
            'fnc':function(){ 
                      updatePosition(spriteID); 
                      drawSprite(spriteID); 
             },
             'something':'here'
            };

var drawOrder= [];
drawOrder.push(data);

There are many functions in this array and they are pushed dynamically depending on what i wish to draw.

What would be the best way to find the index of one of these objects and remove it from the array in this case?

10
  • You want to find an object in your array by its type property? Commented Jan 9, 2016 at 4:23
  • No, the entire object as a whole not just type. That type` is related to my draw function. Edited the code to avoid the confusion :) Commented Jan 9, 2016 at 4:24
  • why drawOrder.indexOf(objYouPush) will not work in your case? Commented Jan 9, 2016 at 4:24
  • Sorry I don't understand your quesion. If you want the best way to find the index, just do drawOrder[n].fnc() Commented Jan 9, 2016 at 4:26
  • @Daniel_L but n implies i already know the index in which case i can just splice it. Commented Jan 9, 2016 at 4:26

2 Answers 2

1

indexOf() returns the index in the array of the element you're searching for, or -1. So you can do:

var index = drawOrder.indexOf("aKey");
if (index != -1)
    drawOrder.splice(index, 1);

Splice:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
indexOf:
http://www.w3schools.com/jsref/jsref_indexof_array.asp

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

Comments

0

I'm not 100% this will answer your question cause is not clear at least to me.

If you want to remove the whole element but you are worried about founding the right index before actually splice the array you should use Array.indexOF

See this code below:

var data  = {
            'fnc':function(){ 
                      updatePosition(spriteID); 
                      drawSprite(spriteID); 
             },
             'type':'aabb'
            };

var drawOrder= [];
drawOrder.push(data);
console.log(drawOrder);
drawOrder.splice(drawOrder.indexOf(data), 1);
console.log(drawOrder);

As the documentation reports:

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.