0

I have an array called collection. This array contains a large number of arrays with a length of 12. Each item of the latter array has - among others - a source ID [0] and target ID [1] (pairs of source and target are unique, but the same source ID can be assigned to different target IDs).

With the source and target IDs given, I need to find the item inside the array with the given IDs and manipulate its values.

jQuery is present if that helps finding the solution.

Thanks in advance!

var collection = [
[
    136898,
    162582,
    "8X1ABG\1",
    "lorem ipsum",
    true,
    "FULL",
    true,
    "FULL",
    "8X1ABG\0",
    "dolor sit",
    false,
    "SIMILAR"
],
[
    136898,
    163462,
    "8X1ABG\1",
    "lorem ipsum",
    true,
    "FULL",
    true,
    "FULL",
    "8X1ABG\0",
    "dolor sit",
    false,
    "SIMILAR"
],  
[
    136578,
    161873,
    "8X1A1G\2",
    "lorem ipsum",
    true,
    "FULL",
    true,
    "FULL",
    "8X1A1G\0",
    "dolor sit",
    false,
    "SIMILAR"
],
[
    136432,
    162280,
    "8X1ABC\1",
    "lorem ipsum",
    true,
    "FULL",
    true,
    "FULL",
    "8X1ABC\0",
    "dolor sit",
    false,
    "SIMILAR"
]]



// TODO: find the unique item in collection array with the following source
// and target ID
var sourceId = 136898;
var targetId = 163462;

// TODO: update some values of the identified item inside collection
2
  • 1
    I'd suggest you change your data structure to an array of objects with named keys. Multi-dimensional arrays like that are a hell to maintain. Commented Jun 14, 2013 at 7:53
  • I am using the array to feed a plugin which handles the data output. Unfortunately this plugin needs arrays to work with. Commented Jun 14, 2013 at 8:12

2 Answers 2

3

Try this:

var item = collection.filter(function(collect) {
  return collect[0] == sourceId && collect[1] == targetId;
});

Again, like I said in the comments, it would better if you change your data structure to an array of objects with named keys then you can do this much more readable:

return collect.sourceId == sourceId && collect.targetId == targetId;
Sign up to request clarification or add additional context in comments.

Comments

1

If you need compatibility to older browsers, since .filter() is supported only by IE9 you can also loop through the elements of the array(or write the implementation of filter, provided by MDN).

var item = [];
for (var i = 0; i < collection.length; i++) {
    var coll = collection[i];
    if (coll[0] == sourceId && coll[1] == targetId) item.push(coll);
}

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.