Home > Software engineering >  How to implement a function that takes an array and some other arguments then removes the other argu
How to implement a function that takes an array and some other arguments then removes the other argu

Time:02-08

Please guys, this is an exercise (exercise 04) from Odin Project. I don't know if there is anything wrong with the code below, it keeps failing the 'npm test' (a test in the terminal) but then i checked it with console.log and it worked.

const removeFromArray= function(...args) {
    const array = args[0];
        const newArray = [];
             array.forEach((item) => {
                 if(!args.includes(item)) {
                      newArray.push(item);  
        }
        });
        return newArray;
    };

CodePudding user response:

It seems to me that I have not understood the question very well. But JS has built-in functions that serve the purpose

Array map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Array filter https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

But from what I see in the code you have to remove the first element from the array.

I suggest you take a look at this question

remove first element from array and return the array minus the first element

CodePudding user response:

I'd suggest using Array.filter() in combination with Array.includes() to achieve the required result.

We filter any element from the input array if it is present in the itemsToRemove array.

function removeFromArray(array, itemsToRemove) {
    return array.filter(element => !itemsToRemove.includes(element));
}

let array = [1,2,3,4,5,6];
let itemsToRemove = [2,4,6];

console.log(removeFromArray(array, itemsToRemove))

We can do this in a more efficient manner if itemsToRemove is very large, using a Set:

function removeFromArray(array, itemsToRemove) {
    const itemsToRemoveSet = new Set(itemsToRemove);
    return array.filter(element => !itemsToRemoveSet.has(element));
}

let array = [1,2,3,4,5,6];
let itemsToRemove = [2,4,6];

console.log(removeFromArray(array, itemsToRemove))

  •  Tags:  
  • Related