简体   繁体   中英

Compare two arrays and append to new array

I have two sets of cards array(a) and array(b) Think of array(a) as a master set, and array(b) the players cards.

I am looping through array(a) and then checking if exists in array(b). If it does not then I deleted from array(a). html binds to the whats left in array(1) the code below works fine for this.

But now I realize array(b) may have duplicates example [cardID:1, cardID:2, cardID:3, cardID:3, cardID:4]

So I added a third array as I want to keep the duplicates as well, I push to a final array. But this code does not get the duplicates cardID3, not sure how to do this?

var i = 0;
var entry1;
    while (i < this.myCardsArray.length) {
       entry1 = this.myCardsArray[i];
          if (this.cardsArray.some(function(entry2) { return entry1.id === entry2.cardID; })) {
              // Found, progress to next
              this.finalCardsArray.push(this.myCardsArray[i]) //added this line to save results
               ++i;
          } else {
              // Not found, remove
              this.myCardsArray.splice(i, 1);
          }
      }
var master_A = [
  {
    cardID: 1,
    extra: 'stuff'
  },
  {
    cardID: 2,
    extra: 'stuff'
  },
  {
    cardID: 3,
    extra: 'stuff'
  },
  {
    cardID: 4,
    extra: 'stuff'
  }
]

given, that the master set has uniqueness on id-s -> I would create a new object, that maps them to their id-s

var master_map_A = {};
master_A.forEach(function(card) {
  master_map_A[card.cardID] = card
})

And then reference them from the slave_B set, for whatever extra information would be necessary, by looping through the list and referencing as master_map_A[card.cardID] ...

var slave_B = [
  {
    cardID: 1
  },
  {
    cardID: 2
  },
  {
    cardID: 3
  },
  {
    cardID: 3
  },
  {
    cardID: 4
  }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM