I've tried this
function removeFromArray(manyMoreArgs, number) {
let i = 0;
while (i < manyMoreArgs.length) {
if (manyMoreArgs[i] === number) {
manyMoreArgs.splice(i, 1);
} else {
i ;
}
}
return manyMoreArgs;
}
console.log(removeFromArray([1, 2, 3, 4], 3)); // result = [1, 2, 4] this removes 3 from array. it works! but then >>
console.log(removeFromArray([1, 2, 3, 4], 3, 2)); // result = [1, 2, 4] this removes 3 from array too but I also want to remove 2 from array
What should I do if I want to remove numbers from array?
CodePudding user response:
You could either define your numbers
parameter as an array
function removeFromArray(manyMoreArgs, numbers) {
let i = 0;
while (i < manyMoreArgs.length) {
if (numbers.includes(manyMoreArgs[i])) {
manyMoreArgs.splice(i, 1);
} else {
i ;
}
}
return manyMoreArgs;
}
console.log(removeFromArray([1, 2, 3, 4], [3]));// result = [1, 2, 4] this removes 3 from array. it works! but then >>
console.log(removeFromArray([1, 2, 3, 4], [3, 2]));// result = [1, 2, 4] this removes 3 from array too but I also want to remove 2 from array
or as a variadic argument
function removeFromArray(manyMoreArgs, ...numbers) {
let i = 0;
while (i < manyMoreArgs.length) {
if (numbers.includes(manyMoreArgs[i])) {
manyMoreArgs.splice(i, 1);
} else {
i ;
}
}
return manyMoreArgs;
}
console.log(removeFromArray([1, 2, 3, 4], 3));// result = [1, 2, 4] this removes 3 from array. it works! but then >>
console.log(removeFromArray([1, 2, 3, 4], 3, 2));// result = [1, 2, 4] this removes 3 from array too but I also want to remove 2 from array
CodePudding user response:
I think you can make use of a JavaScript function that takes in these two arrays and filters the first to contain only those elements that are not present in the second array. And then return the filtered array.
const removeNum = (arr,...numbers) =>{
const arr2 = [...numbers]
console.log(arr2);
numbers = arr.filter(el => {
return arr2.indexOf(el) === -1;
});;
console.log(numbers);
}
removeNum([1, 2, 3, 4], 3, 2)
CodePudding user response:
Here is my version
const isNumeric = (n) => !isNaN(n);
let array = [3, 4, "string", true];
let newArr = array.filter((elem) => isNumeric(elem) !== true);
console.log(newArr); // ['string']