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!!
-
Possible duplicate of Find object by id in array of javascript objectsabc123– abc1232015年12月17日 18:15:05 +00:00Commented Dec 17, 2015 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– Katana3142015年12月17日 18:17:35 +00:00Commented Dec 17, 2015 at 18:17
-
@Katana314 the code in the question has so many issues it's hard to say what the main issue is :-)jcaron– jcaron2015年12月17日 18:21:39 +00:00Commented Dec 17, 2015 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– abc1232015年12月17日 18:21:44 +00:00Commented Dec 17, 2015 at 18:21
2 Answers 2
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.
Comments
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(','));