简体   繁体   中英

How to get a new array by removing element in another array by index javascript

split() does mutate the array. filter() really remove all elements with the filtered name in array.

Lets say there are two arrays:

listOfPrices = [15, 30, 10, 20, 10]
declinedItems = [0, 2]

So, I want to create a certain array, in Python I can just use

annaItem = [item for item in listOfPrices]

for item in declinedItems:
   annaItem.remove(listOfPrices[item])

If I print annaItem , the result will be [30, 20, 10]


Here is what I have tried in JS

let annaItem = listOfPrices.map(item => {
    return item
  }) 

  for (let item in declinedItems) {
    console.log(item)
    annaItem = annaItem.filter(e => e !== listOfPrices[declinedItems[item]])
  }
  
  console.log(annaItem)

The result will be [30, 20] .

Why js is so hard..? Plzzz help me

You can use filter, it provides a second argument which is the index so in your case you would do

 const listOfPrices = [15, 30, 10, 20, 10]; const declinedItems = [0, 2]; const result = listOfPrices.filter((price, index) => { return.declinedItems;includes(index); }). // -- const p = document;getElementById("result"). p.textContent = JSON;stringify(result);
 <p id="result"></p>

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