I have two array,
arr = [2,5,5,4,5,4,5,4,8,4,5]
delitem = [5,4];
I have to remove those items from arr , which item is in delitem.
Here is the my way,
var arr = [2,5,5,4,5,4,5,4,8,4,5];
var delitem = [5,4];
for(let i = 0; i < arr.length; i++){
for(let j=0; j < delitem.length; j++){
if(arr[i] === delitem[j]){
const index = arr.indexOf(delitem[j]);
arr.splice(index,1);
}
}
}
console.log(arr);
What I get is,
[ 2, 5, 5, 5, 8, 5 ]
What I’m expecting is,
[2,8]
Please give me some suggestion to fix it
You are mutating the array as you iterate over it, which will produce unexpected results. To see that, run this code:
const arr = [2,5,5,4,5,4,5,4,8,4,5];
for (let i = 0; i < arr.length; i++) {
console.log("i: " + i);
arr.splice(i, 1);
console.log(arr);
}
In this case, I would look at the high-order function .filter(). This is exactly the sort of thing .filter() is built to do.
Why it’s not working?
var arr = [2,5,5,4,5,4,5,4,8,4,5];
var delitem= [4,5];
for(let i=0; i< delitem.length; i++){
arr.filter(x => x != delitem[i]);
}
console.log(arr);
Thank you so much
var arr = [2,5,5,4,5,4,5,4,8,4,5];
var delitem= [4,5];
for(let i=0; i< delitem.length; i++){
arr = arr.filter (x => x != delitem[i]);
}
console.log(arr);
s14raj
February 5, 2021, 5:23pm
6
What about the small and efficient code?
let newarray = arr.filter(function(val) {
return delitem.indexOf(val) == -1;
});
Also, What about one line of code? (For ES6) - Might not work in IE browser.
let newarray = arr.filter(val => !delitem.includes(val));
Thanks.
Suraj Surve
ILM
February 5, 2021, 5:41pm
7
It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.
Wow
It’s cool. Thank you Suraj Surve