When to use an object and an array

I have a situation where I have 3 different arrays with a very large number of objects. I read a lot of questions and blog posts about this, but I still don't know when to use what.

PS! My biggest problem is that I need iteration and push (perfect for arrays), and also find if exists in the array and delete (more suitable for objects). No specific order is required.

I cannot allow to have the same object in array1and array1clicked because they have to perform different actions.


When is the best way to use an object and an array in my example? What should I replace with an object and what should remain an array? I'm sure the number of objects in it also matters, right?


My current code is:

//Objects in arrays are literally custom {objects} with custom prototypes and html
var array1 = [ 20 objects ];
var array1clicked = [];

var array2 = [ 250 objects ];
var array2clicked = [];

var array3 = [ 50 000 objects ];
var array3clicked = [];

//Each object in arrays has event attached
objecthtml.click(function() {
    //Add to clicked array
    array1clicked.push(thisobject);
    //Remove from initial array
    var index = array1.indexOf(thisobject);
    if (index > -1) {
        array1.splice(index, 1);
    }
}
//Same with array2 and array3 objects


//Iterations on different conditions
var array1count = array1.length;
var array1clickedcount = array1clicked.length;

//Same with array2 and array3

if(condition1) {
   for(a = 0; a < array1count; a++) {
       array1[a].div.style.visibility = 'hidden';
   }
   //Same with array2 and array3 objects

   for(a = 0; a < array1clickedcount; a++) {
       array1clicked[a].div.style.visibility = 'visible';
   }
   //Same with array2clicked and array3clicked objects
}
else if(condition2) {
   for(a = 0; a < array1count; a++) {
       array1[a].div.style.visibility = 'visible';
   }
   //Same with array2 and array3 objects

   for(a = 0; a < array1clickedcount; a++) {
       array1clicked[a].div.style.visibility = 'hidden';
   }
   //Same with array2clicked and array3clicked objects
}
+4
source share
2 answers

It seems you need a data structure with these operations:

  • Iteration
  • Embed
  • Delete
  • Search

With arrays, the problem is that finding and deleting (with reindexing) is slower.

The problem with objects is that property names can only be strings.

The ideal structure is a set.

var s = new Set();
s.add(123); // insert
s.has(123); // search
s.delete(123); // delete
s.values(); // iterator
+5
source

In your case, I think you only need to use Array.

, , , Array.

0

Source: https://habr.com/ru/post/1625907/


All Articles