Reputation: 2124
Performance is very key and I was hoping there would be a better way to update an array via an Id. I'm looking for a better version of the update function (shown below) that doesn't need to iterate through the 2nd array so many times.
I've added example snippet below to show what I'm trying to do. Keep in mind that these arrays can potentially contain potentially hundreds of objects and need to be updated several times a second.
var array1 = [{
id:"asd4567wds8",
x: 109,
y: 763,
/* These values also have other properties that I need to keep */
}, {
id:"df567wgfdz4",
x: 450,
y: 132,
/* These values also have other properties that I need to keep */
}, {
id: "cvbz5476zzg",
x: 903,
y: 865,
/* These values also have other properties that I need to keep */
}]
var array2 = [{
id:"df567wgfdz4",
x: 450,
y: 137
},{
id:"asd4567wds8",
x: 114,
y: 763
}, {
id: "cvbz5476zzg",
x: 908,
y: 870
}]
$("document").ready(function(){
display();
$("#update").click(function(){
update();
display();
})
})
/*************************************
* Is there a better way to do this? *
*************************************/
function update(){
array1.forEach(function(element){
var temp = array2.find(function(element2){
return element.id === element2.id
})
element.x = temp.x
element.y = temp.y
})
}
function display(){
$("#Array1").empty();
$("#Array2").empty();
array1.forEach(function(element){
var p = $("<span>").text(`[${element.x}, ${element.y}]`)
$("#Array1").append(p)
})
array2.forEach(function(element){
var p = $("<span>").text(`[${element.x}, ${element.y}]`)
$("#Array2").append(p)
})
if(test(array1, array2)){
$("#test").text("Success!")
} else {
$("#test").text("Values do not match")
}
}
/* Test function do not change */
function test(array1, array2){
var clear = true;
array1.forEach(function(element){
var temp = array2.find(function(element2){
return element.id === element2.id
});
clear = (element.x === temp.x && element.y === temp.y)?clear:false
});
return clear;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="Array1">Array 1: </div>
<div id="Array2">Array 2: </div>
<button id="update">
Update
</button>
<h3 id="test"></h3>
</body>
Context: I'm creating a game utilizing sockets and I want to update the client with the new locations of the other objects of the game in one huge chunk.
Upvotes: 0
Views: 493
Reputation: 167
You could also run the map function on one or both of the arrays so that you can get the structure that @Doug mentioned.
object2 = { "df567wgfdz4" : { x: 450, y: 137 }, "asd4567wds8" : { x: 114, y: 763 }, "cvbz5476zzg": { x: 908, y: 870 }
The map function to get the above would look something like this:
array2.map(newObj => {
var rObj = {};
var sObj = {};
sObj['x'] = newObj.x;
sObj['y'] = newObj.y;
rObj[newObj.id] = sObj;
return rObj;
});
Upvotes: 1