0

I have an array and an array of objects. I want to search each value in the array in the array of objects and if it doesnt exist, I want to remove the value from the array.

var arr= [1,2,3,4];

var recs = [{id:1},{id:2},{id:3}]; //4 doesnt exist in recs, remove from arr

//arr = [1,2,3];

Heres my attempt. Obviously does not work. I am not sure how I can compare each arr index with all the values in recs before moving on the next arr index:

var arr= [1, 2, 3, 4], index;

var recs = [{a:1},{a:2},{a:3}];

for(var i = 0; i<arr.length; i++){
  for(var val in recs[i]){
    if(arr[i] != recs[i][val]){
      index = arr.indexOf(arr[i]);
      arr.splice(index, 1);          
    }
  }
}

thank you!!

abc123
  • 17,855
  • 7
  • 52
  • 82
stackato
  • 1,085
  • 1
  • 19
  • 38
  • Possible duplicate of [Find object by id in array of javascript objects](http://stackoverflow.com/questions/7364150/find-object-by-id-in-array-of-javascript-objects) – abc123 Dec 17 '15 at 18:15
  • @abc123 I think the question has more to do with looping through an array and *removing elements* (the hard part) than it does to do with finding objects. – Katana314 Dec 17 '15 at 18:17
  • @Katana314 the code in the question has so many issues it's hard to say what the main issue is :-) – jcaron Dec 17 '15 at 18:21
  • @Katana314 answer two on the above literally shows how to go through an create the array that he wants...removing would be 1 extra step. – abc123 Dec 17 '15 at 18:21

2 Answers2

4

If you are okay with leaving your original array instance alone and creating a new one (essentially treating it as immutable)

var newArr = arr.filter(function(num) {
  return !recs.every(function(obj) {
    return obj.a !== num;
  });
});

Detail of the methods used: Array.filter is passed a function, runs that function on each element inside, and then returns a new array with only the elements that returned true in the function.

Array.every works a little similar, but returns a Boolean, true or false. It returns true if all of the elements of the array returned true inside of the function.

Katana314
  • 8,429
  • 2
  • 28
  • 36
0
var arr= [1, 2, 3, 4];

var recs = [{a:1},{a:2},{a:3}];

// don't use var in for loops.
// Variables declared with var have function scope, so declare them at the top of your function
var i;
var j;
var value;
var found;
// iterate over the array
for (i = 0; i < arr.length; i++)
{
  value = arr[i];
  found = false;
  // iterate over the other array
  for (j = 0 ; j < recs.length ; j++)
  {
    // if we found what we were looking for, make a note and exit loop
    if (recs[j].a == value)
    {
      found = true;
      break;
    }
  }
  if (!found)
  {
    arr.splice(i, 1);
    // To compensate the loop's i++, to avoid skipping the next entry
    i--;
  }
}
alert(arr.join(','));
jcaron
  • 17,302
  • 6
  • 32
  • 46