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
CodePudding user response:
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>