简体   繁体   中英

How to use a key array to remove specific items from a main array?

First of all thank you to whoever reads this whole question. I am having trouble writing a function that can take a key array and use the indices to remove like items from a main array.

My main Array

var mainArray = [
    {fruit:"apple",color:"red"}, 
    {fruit:"orange",color:"orange"}, 
    {fruit:"banana",color:"yellow"}, 
    {fruit:"apple",color:"red"}, 
    {fruit:"banana",color:"yellow"},
    {fruit:"mango",color:"greenishyellowishred"}
]

Array of items will be added to this mainArray and I need to remove multiple items at a time.

My key Array

var keyArray = [{fruit:"apple",color:"red"}, {fruit:"banana",color:"yellow"}]

I am attempting to remove the "apple" and the "banana" by using a for loop to decrement through the array to maintain the integrity of the mainArray .

 for(var i = mainArray.length - 1; i > -1; i--) {
    for(var j = keyArray.length - 1; j > -1; j--) {     
      if(mainArray[i].fruit === keyArray[j].fruit) {
        mainArray.splice(i, 1)
        keyArray.splice(j, 1)
      }
    }
 }

My issue comes when I am trying to read mainArray[i].fruit if i = 0

Thanks in advance for any help possible.

Try the following way:

 var mainArray = [ {fruit:"apple",color:"red"}, {fruit:"orange",color:"orange"}, {fruit:"banana",color:"yellow"}, {fruit:"apple",color:"red"}, {fruit:"banana",color:"yellow"}, {fruit:"mango",color:"greenishyellowishred"} ]; var keyArray = [{fruit:"apple",color:"red"}, {fruit:"banana",color:"yellow"}]; var tempArray = []; for(let j = 0; j < keyArray.length; j++) { for(let i = 0; i < mainArray.length; i++) { if(mainArray[i].fruit === keyArray[j].fruit) { tempArray.push(mainArray[i]); } } } mainArray = mainArray.filter( function( el ) { return !tempArray.includes( el ); }); console.log(mainArray); 

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