Adu Rao Adu Rao - 24 days ago 8
Javascript Question

Check if list of array exists in the array of objects

I have the following array

var data = ["004", "456", "333", "555"];


I also have an array of object like this.

Object {Results:Array[2]}
Results:Array[2]
[0-1]
0:Object
id="004"
name: "Rick"
Active: "false"
1:Object
id="005"
name:'david'
Active: "false"


As you can see, id with 004 consists in array as well as in object. I want to check how many elements from the array 'data' are present in the object 'Results.

The final result should be

data = ["004"];


Can anyone let me know how to search for this

Answer

without underscore.js

var data = ["004", "456", "333", "555"];
arr = [{
  id: "004",
  name: "Rick",
  Active: "false"
}, {
  id: "005",
  name: 'david',
  Active: "false"
}];

out = [];
for (var i = 0; i < arr.length; i++) {
  for (var j = 0; j < data.length; j++) {
    if (arr[i].id === data[j])
      out.push(data[j]);
  }
}
console.log(out);

With underscore.js

var data = ["004", "456", "333", "555"];
arr = [{
  id: "004",
  name: "Rick",
  Active: "false"
}, {
  id: "005",
  name: 'david',
  Active: "false"
}];

out = [];

_.each(arr, function(value1, key1, obj1) {
  _.each(data, function(value, key, obj) {
    if (value1.id == value) out.push(value);
  });
});

console.log(out);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://underscorejs.org/underscore-min.js"></script>

Comments