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?
}
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];
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With