Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and move an object in javascript array by id of an objects

I have 2 arrays of objects. Each object has an Id property. Now, if I have a 3rd array of just Ids, what is the better and faster way of finding objects from array1 based on those Ids and moving them to array2.

Thanks a lot for answering..

Sample code:

Person = function(id, fn, ln) {
  this.id = id,
  this.firstName = fn,
  this.lastName = ln
}

array1 = new Array();
// add 500 new Person objects to this array

array2 = new Array();
// add some other new Person objects to this array

function moveArrayItems(ids) {
  // ids is an array of ids e.g. [1,2,3,4,5,6,...]
  // Now I want to find all the person objects from array1 whose ids 
  // match with the ids array passed into this method. Then move them to array2.
  // What is the best way to achive this?
}
like image 375
Bharat Avatar asked Dec 29 '22 04:12

Bharat


1 Answers

If you really have 500+ objects in each array, you're probably better off using a hash to store the objects, keyed by id:

var people = {
              1: {id:1, name:"George Washington"},
              2: {id:2, name:"John Adams"},
              3: {id:3, name:"Thomas Jefferson"},  // ...
             } 

var people2 = {}

Now it's trivial (and much, much faster) to move things around by ID:

function moveArrayItems(ids) {
    var i,id;
    for (i=0; i<ids.length; i++){
        id = ids[i];
        if (people1[id]) {
            people2[id] = people1[id];
            delete people1[id];
        }
    }
}
like image 74
Kenan Banks Avatar answered May 15 '23 18:05

Kenan Banks