最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript remove object from array if value exists in other array - Stack Overflow

programmeradmin3浏览0评论

I am using Firebase, so if there is a more efficient way to structure this data in order to be able to query only the cards that have not already been viewed by the logged in user, I am open to going that route as well. Right now I am trying to do the filtering after the fact.

I have an array of all cards included in my application that looks like this:

I have a second array that holds information on all the cards the user has already seen. I want to be able to look through both arrays, and if the cid in Array two matches the $id in Array 1, then remove that object entirely from Array 1.

I am using Firebase, so if there is a more efficient way to structure this data in order to be able to query only the cards that have not already been viewed by the logged in user, I am open to going that route as well. Right now I am trying to do the filtering after the fact.

I have an array of all cards included in my application that looks like this:

I have a second array that holds information on all the cards the user has already seen. I want to be able to look through both arrays, and if the cid in Array two matches the $id in Array 1, then remove that object entirely from Array 1.

Share Improve this question asked Aug 27, 2016 at 3:12 user2994560user2994560 1,3095 gold badges18 silver badges30 bronze badges 1
  • you can follow my answer. and it was same as the one you have accepted. – Rafi Ud Daula Refat Commented Aug 27, 2016 at 5:16
Add a ment  | 

3 Answers 3

Reset to default 9

This is actually very easy to do in a functional way:

array1 = array1.filter(item => array2.every(item2 => item2.cid != item.$id));

Array.prototype.filter() returns, as an array, the elements of an array that cause the supplied function to return true. And our filter-evaluator says 'return true if there is no item in array2 whose CID matches this item's ID'.

Because filter() is returning a new array, there's no need to use splice(); we can just reassign array1 to the newly filtered array.

Loop through the arrays and use splice to remove the element

for(var i =0; i< array2.length; i++ ) {
   for(var j= 0; j< array1.length;j++) {
     if (array2[i].$id === array1[j].$id) {
      array1.splice(j,1);
      break;
    }
  }

Why dont you use one array of objects for that. keep a object key for that

seen

by default keep seen false. and use firebase-query where the column seen is false.

or you can do something like that after fetching the data in your code.

var resultarray = [];

for(var i =0; i< array1.length; i++ ) {
   var flag = true;
   for(var j= 0; j< array2.length;j++) {
     if (array1[1].$id === array2[2].$id) {
       flag = false;
       break;
    }
  }
  if(flag === true) {
    resultarray.push(array1[i]);
  }
}
发布评论

评论列表(0)

  1. 暂无评论