1

I encountered some difficulties while trying to find a good logic to update an array of objects in Javascript.
I obtain the first array by doing a request to the server. I get an array of objects like the following one:

{id: 2, text: 'some text'}  //Object

And this is what the array looks like:

[Object, Object, Object]    

These objects are turned into html.
After a while, it does a second request and gets a new list of data objects. How can I synchronize the old list with the new one? What I mean by synchronizing is: remove the objects that don't exist anymore, and the associated html part as well, and insert the nodes that are not currently present in the right position.

4
  • Is the id unique to each object? Commented Jul 13, 2012 at 16:43
  • And what does the HTML look like? Commented Jul 13, 2012 at 16:46
  • <div class="item-id" id="item-id-{id}"><div class="content">{text}</div></div>. This is not relevant for this problem anyway. I know how to synchronize the html, I don't know how to synchronize the arrays. The curly braces are replaced with content requested via ajax. Commented Jul 13, 2012 at 16:49
  • Ah ok, I sounded like you were asking about the HTML side as well Commented Jul 13, 2012 at 16:50

1 Answer 1

2

You can find both added and removed items like this:

var origArray = [...];   // assume first set of data is in origArray
var newArray = [...];    // second set of data is in newArray

function makeMap(array, key) {
    var map = {};
    for (var i = 0; i < array.length; i++) {
        map[array[i][key]] = true;
    }
    return(map);
}

function compareArrayToMap(array, map) {
    var item, var results = [];
    for (var i = 0; i < array.length; i++) {
        item = array[i];
        if (!(item.id in map)) {
            results.push(item);
        }
    }
    return(results);
}

// build id map for each array
var origMap = makeMap(origArray, "id");
var newMap = makeMap(newArray, "id");

// find items that have been removed
var removedItems = compareArrayToMap(origArray, newMap);

// find items that have been added
var addedItems = compareArrayToMap(newArray, origMap);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.