odin-javascript-exercises/04_removeFromArray/solution/removeFromArray-solution.js

29 lines
1,001 B
JavaScript
Raw Normal View History

2022-02-20 11:07:44 -08:00
// we have 2 solutions here, an easier one and a more advanced one.
2023-01-21 09:53:41 -08:00
// The easiest way to get an array of the rest of the arguments that are passed to a function
2022-02-20 11:07:44 -08:00
// is using the rest operator. If this is unfamiliar to you look it up!
2023-01-21 09:53:41 -08:00
const removeFromArray = function (array, ...args) {
// create a new empty array
const newArray = [];
// use forEach to go through the array
array.forEach((item) => {
// push every element into the new array
// UNLESS it is included in the function arguments
// so we create a new array with every item, except those that should be removed
if (!args.includes(item)) {
newArray.push(item);
}
});
// and return that array
return newArray;
2022-02-20 11:07:44 -08:00
};
// A simpler, but more advanced way to do it is to use the 'filter' function,
// which basically does what we did with the forEach above.
2023-01-21 09:53:41 -08:00
// var removeFromArray = function(array, ...args) {
2022-02-20 11:07:44 -08:00
// return array.filter(val => !args.includes(val))
// }
//
module.exports = removeFromArray;