1

I need to compare a string array of ids to a array of objects. I need the objects with matching ids to be returned into a object. I need to use linq.js and not sure how to do this.

String array that I need to compare against:

selectedIds = ["080A8", "032A10", "025A10"]

Array I need to loop through and return matching objects:

[
 {"id":"009B4",
     "supply":{
       "builder":[
             {"id":"3629",
              "name":"sample name",
              "color":"red"}
                 ]
             }
 },
 {"id":"00434",
     "supply":{
       "builder":[
             {"id":"34529",
              "name":"sample name two",
              "color":"black"}
                 ]
             }
   }
]

I need to match the id that is on the top level.

This is what I am trying to start with:

var selectedObjects = Enumerable.From(array).Where("m=>m.id == '" +  + "'").ToArray();
Matt Tester
  • 4,663
  • 4
  • 29
  • 32
texas697
  • 5,609
  • 16
  • 65
  • 131

1 Answers1

3

You don't need Linq.js nor any library for that matter to achieve your aim. Here's a solution that solves the problem in O(n) time, where n is the size of the largest array.

var selectedIds = ["080A8", "032A10", "025A10"];
var list = [
    {"id": "009B4",
        "supply": {
            "builder": [
                {"id": "3629",
                    "name": "sample name",
                    "color": "red"}
            ]
        }
    },
    {"id": "00434",
        "supply": {
            "builder": [
                {"id": "34529",
                    "name": "sample name two",
                    "color": "black"}
            ]
        }
    }
];

var idMap = selectedIds.reduce(function (map, id) {
    map[id] = true;
    return map;
}, {});

var selectedObjects = list.filter(function(item){
    return !!idMap[item.id];
});
Igwe Kalu
  • 14,286
  • 2
  • 29
  • 39